五、数据查询select

1、 查看当前正在使用的数据库:

select database();

2、select 语句查询表中数据

select  字段名  from 表名;          #只查询相应的字段,其他字段数据不显示

select  *   from 表名;             #使用通配符(*)查询整张表所有字段的数据 

可查询多个字段,字段之间以逗号( , )隔开

3、检索的数据去重

使用关键字(distinct)检索某个字段中不同的行,即返回唯一值

select distinct 字段名  from 表名; 
  • distinct 关键字必须放在字段名前面,只用于 select 语句
  • distinct 关键字用于所有字段,而不只是前置它的字段
select distinct name, id from A;  #实际上是根据“name+id”来去重,distinct同时作用在了name和id上,去重列组

select id, distinct name from A;   #会提示错误,因为distinct必须放在字段名前面

 4、返回指定的行数据

select语句中强制返回指定的行记录数

命令: select  字段名  from 表名  limit  X,N ;               

1)limit 接受一个或两个数字参数。参数必须是一个整数常量。

2)如果只有一个参数,则表示只返回前X行记录;

3)给定两个参数,第一个参数指定从第一个返回记录行的偏移量开始查询,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1)

MariaDB [test]> select * from t1;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  1 | q    |      |
|  2 | w    |      |
|  3 | er   | male |
|  4 | e    |      |
+----+------+------+
4 rows in set (0.00 sec)

MariaDB [test]> select * from t1 limit 1;
+----+------+-----+
| id | name | sex |
+----+------+-----+
|  1 | q    |     |
+----+------+-----+
1 row in set (0.00 sec)

MariaDB [test]> select * from t1 limit 1,2;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  2 | w    |      |
|  3 | er   | male |
+----+------+------+
2 rows in set (0.00 sec)

MariaDB [test]> select * from t1 limit 2,2;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  3 | er   | male |
|  4 | e    |      |
+----+------+------+
2 rows in set (0.00 sec)

5、使用完全限定的表名

完全限定可用于:

 1)库名 . 表名     (同时使用库名和表名)

 2)表名 . 字段名  (同时使用表名和字段名)

select 表.字段名 from 库.表      #在当前数据库中检索其他数据库中表的数据

select 表.字段名 from 表名    等价于   select 字段名 from 表名
posted @ 2021-03-25 22:22  chao_xiong  阅读(305)  评论(0)    收藏  举报