MySQL单表数据查询

在MySQL数据查询中,最基本的查询语句是:

select * from table_name where condition;

假设数据库中表students中有id, name, age, birthday四个字段

*代表表中所有字段,在查询时可结合实际选取自己需要查询的字段,即:

select name, id, age from students;

在查询时,输入的字段顺序即为查询结果显示的顺序。

如果某个字段下的数据有重复,但我们只想看到不重复的,可使用关键字distinct:

select distinct name age from students;

似乎distinct后只能跟着一个字段名 ,用distinct同时查询多个字段暂时还没看到;

在MySQL中也可以使用简单的四则运算,如:

select name, age-18 from students;

可以给进行四则运算后的字段名添加别名:

select name, age-18 as child from students;

其实在上述语句中as也可以不写,写上似乎只是稳了增加理解和可读性;

与python类似,MySQL也也可以设置显示格式,和字符串拼接差不多:

select concat(name, '同学的年龄是: ', age-18) falseage from students;

concat()提供拼接字符串和数值的功能。

在MySQL中支持带关系运算符和逻辑运算符的条件数据查询,如<,>, and,  or, not等, 都是在最后的where子句中实现的;

select name, age from students where id>10 ;
select name from students where age between 10 and 20;

上面代码查询了年龄在10到20岁学生的姓名。

查询年龄不在此范围的学生,可以使用not:

select name from age not between 10 and 20;

可使用关键字not null, 实现判断字段的数值是否为空的条件查询。

select name from students where age is null;

相反,可使用not找到与此相反的结果:

select name from students where age is not null;

或者:

select name from students where not age is null;

in关键字提供了集合查询:

select name from students where age in (18,19,27,25)

该语句查询了年龄在这四个数值的学生姓名;其实使用or关键词也可以达到相同的效果,但是会造成语句过长。

如果需要查询不在该集合中的数据,可在in前加上not;

使用like的模糊查询:

"_"通配符,该通配符能匹配单个字符;

"%"通配符可以匹配任意长度的字符串。

select name from students where name like 'A%';

查询名字以A开头的学生姓名;

like模糊查询可以和not关键字配合使用,达到相反的效果。

在查询时,查询结果根据数据最初记录的顺序来显示,可以使用order by关键词来设置升序或者降序排序:

select field1, field2, field3 from table_name where condition order by filed desc;

order by field desc为按照field降序排序,如果写为order by field;则为升序排序,即默认为升序(asc)。

也可按照一个字段升序,一个字段降序同时排序:

select * from table_name where condition order by field1 by asc, field2 desc;

通过limit关键字限制查询结果的显示数量:

select name from students where age>18 limit offset_start, row_count;

如:

select * from students where age is null order by name limit 5, 5;
原文地址:https://www.cnblogs.com/jdwfff/p/10516858.html