☞ 语法
# " * " 代表返回表中所有字段的数据 select * from tb_name;☞ 示例
mysql> select * from student; +------+--------+------+ | num | name | age | +------+--------+------+ | 2 | 李娜扎 | 33 | | 3 | 王大锤 | 700 | | 4 | 牛魔王 | 1000 | +------+--------+------+ 3 rows in set (0.04 sec)☞ 注意
如果不查询表中所有的列,尽量避免使用 SELECT *,因为它会进行全表扫描,不能有效利用索引,增大了数据库服务器的负担,以及它与应用程序客户端之间的网络 IO 开销。
☞ 语法
# tb_name 表中需要查询的字段 select field_1, field_2 from tb_name;☞ 示例
mysql> select name, age from student; +--------+------+ | name | age | +--------+------+ | 李娜扎 | 33 | | 王大锤 | 700 | | 牛魔王 | 1000 | +--------+------+ 3 rows in set (0.04 sec)在创建数据表时,一般都会使用英文单词或英文单词缩写来设置字段名,在查询时列名都会以英文的形式显示,我们可以给列名起别名,增强阅读性。
☞ 语法
# 用中文名代替字段名,其中 as 可以省略 select col_name [as] chinese_name from tb_name;☞ 示例
mysql> select num as '序号', age '年龄' from student; +------+------+ | 序号 | 年龄 | +------+------+ | 2 | 33 | | 3 | 700 | | 4 | 1000 | +------+------+ 3 rows in set (0.04 sec)☞ 注意
① 别名可以使用引号引起来(单双皆可),也可以不使用。 ② 别名中有特殊符号的,比如空格,此时别名必须用引号引起来。 ③ 尽量不要省略 as,方便阅读。
☞ 注意
关键字 where 后面跟上一个或者多个条件,条件是对前面数据的过滤,只有满足 where 后面条件的数据才会被返回。
☞ 注意
① 空值查询需要使用 IS NULL 或者 IS NOT NULL,其他查询运算符对 NULL 值无效 ② 建议创建表的时候,尽量设置表的字段不能为空,给字段设置一个默认值。 ③ LIKE 中的 % 可以匹配一个到多个任意的字符,_ 可以匹配任意一个字符,需要使用引号整体引起来。 ④ <=> 既可以判断 NULL 值,又可以判断普通的数值,但可读性较低,不推荐使用。
☞ ==、<>
mysql> select num as '序号', age '年龄' from student where num = 3; +------+------+ | 序号 | 年龄 | +------+------+ | 3 | 700 | +------+------+ 1 row in set (0.03 sec) mysql> select num as '序号', age '年龄' from student where num <> 3; +------+------+ | 序号 | 年龄 | +------+------+ | 2 | 33 | | 4 | 1000 | +------+------+ 2 rows in set (0.04 sec)☞ BETWEEN AND
mysql> select num as '序号', age '年龄' from student where age between 700 and 1000; +------+------+ | 序号 | 年龄 | +------+------+ | 3 | 700 | | 4 | 1000 | +------+------+ 2 rows in set (0.03 sec)☞ IN
mysql> select num as '序号', age '年龄' from student where age in (700, 800, 900, 1000); +------+------+ | 序号 | 年龄 | +------+------+ | 3 | 700 | | 4 | 1000 | +------+------+ 2 rows in set (0.03 sec)☞ LIKE
mysql> select num as '序号', name as '姓名', age as '年龄' from student where name like '%唐%'; +------+-----------+------+ | 序号 | 姓名 | 年龄 | +------+-----------+------+ | 2 | 李娜扎·唐 | 33 | +------+-----------+------+ 1 row in set (0.04 sec)☞ IS NULL、IS NOT NULL
mysql> select * from student; +------+----------+------+ | num | name | age | +------+----------+------+ | 2 | 李娜扎·唐 | 33 | | 3 | 王锤锤·明 | 700 | | 4 | NULL | 1000 | +------+----------+------+ 3 rows in set (0.03 sec) mysql> select num as '序号', name as '姓名', age as '年龄' from student where name is null; +------+------+------+ | 序号 | 姓名 | 年龄 | +------+------+------+ | 4 | NULL | 1000 | +------+------+------+ 1 row in set (0.04 sec) mysql> select num as '序号', name as '姓名', age as '年龄' from student where name is not null; +------+----------+------+ | 序号 | 姓名 | 年龄 | +------+----------+------+ | 2 | 李娜扎·唐 | 33 | | 3 | 王锤锤·明 | 700 | +------+----------+------+ 2 rows in set (0.03 sec)