MySQL数据库 单表数据记录查询

50 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第17天

1:查询所有字段

select from table_name;

 2:查询指定字段 

select name from goods;

图片.png

select distinct type from goods;

图片.png

如果要同时查询表中两个字段,则所要查询的字段之间要用逗号隔开

select id,name from goods;

3:查询指定记录

 select * from goods where id = 3;

图片.png

4:

 select * from goods where  type = '糖类';

图片.png

5:

 select * from goods where price =1230 ;

图片.png

6:

 select *from goods where price=2.5;

图片.png

7:

  select  *  from  goods  where add_time is NULL;

图片.png

8:

 select * from goods where num is not null;

图片.png

9:多条件查询,MySQL支持多条件查询。如果条件之间使用and 关键字连接,那么只有符合所有条件的记录才会被返回。如果多条件查询中的条件使用 or 关键字进行连接,表示只需要符合所有条件中的一个条件,记录就会被返回。其中,and 关键字可以使用符号 “&&”来代替,or 关键字可以使用符号“||”来代替。

 select * from goods where type='糖类' || type='书籍';

图片.png

10:使用in 关键字可以查询字段值等于指定集合中任意一个值的记录,语法形式为

select * from table_name where col_name in (value1,value2,....valuen);

or 关键字和in 关键字可以实现相同的功能,但是in 关键字可以使查询语句更加简洁,并且in 关键字的执行速度要比 or 的关键字快。另外,in 关键字还可以与not 关键字配合使用,作用是查询字段值不在指定集合中的记录。

 select * from goods where id in (1,2,5,8,9);

图片.png

11:范围查询,使用的是between 关键字,用于查询字段值在某个范围内的记录,语法形式为

    select * from tablename  where col_namea between value1 and value2;

 select * from goods where price between 1 and 50;

图片.png

12:

 select * from goods where price >=1 and price <=50;

图片.png

13:

select * from goods where price<=1 or price>=50;

图片.png

14:字符匹配查询,使用like 关键字又称为模糊查询,通常用于查询字段值包含某些字符的记录,语法形式为

    select * from table_name where colnamea like valueb;
其中,vvalueb 表示要匹配的字符,like 关键字 一般与通配符“%”或者“_” 配合使用,如果字段col_namea 中值包含 valueb,此条记录就会被返回,通配符可以放在字符前,也可以放在字符后,还可以放在字符前后。通配符“%”可以匹配任意长度的字符,可以是0个,也可以是一个或多个。
 select * from goods where name like '%汁';

图片.png

15:查询结果不重复:MySQL提供了distinct 关键字,使得查询结果不重复,其语法形式

    select distinct col_list from table_name;

16:单字段排序 执行sql语句,查询goods 表中id、name和add_字段的数据,并按照add_time 字段值进行排序,例如

select id,name,add_time from goods order by add add_time;

图片.png

17:多字段排序,查询 goods 表中所有的记录,并按照 price 和num 字段值进行排序,例如

select * from goods order by price,num;

图片.png

通过查询结果可以看出,系统会首先按照price 字段值进行排序,对于price 字段值相同的记录,再按照num 字段值进行排序。

18:按照num字段的升序和add_time 字段的降序

select * from goods order by num asc,add_time desc;

图片.png

19:执行sql语句,将goods表中所有的记录查询出来,并按照price字段降序排序

select * from goods order by price desc;

在按照多字段排序时,也可以使用desc 关键字进行排序降序。