select 语句常用来根据一定的查询规则到数据库中获取数据, 其基本的用法为:
select 列名称 from 表名称 [查询条件];
例如要查询 students 表中所有学生的名字和年龄, 输入语句 select name, age from students; 执行结果如下:
mysql> select name, age from students; +--------+-----+ | name | age | +--------+-----+ | 王刚 | 20 | | 孙丽华 | 21 | | 王永恒 | 23 | | 郑俊杰 | 19 | | 陈芳 | 22 | | 张伟朋 | 21 | +--------+-----+ 6 rows in set (0.00 sec) mysql>
也可以使用通配符 * 查询表中所有的内容, 语句: select * from students;
where 关键词用于指定查询条件, 用法形式为: select 列名称 from 表名称 where 条件;
以查询所有性别为女的信息为例, 输入查询语句: select * from students where sex="女";
where 子句不仅仅支持 "where 列名 = 值" 这种名等于值的查询形式, 对一般的比较运算的运算符都是支持的, 例如 =、>、<、>=、<、!= 以及一些扩展运算符 is [not] null、in、like 等等。 还可以对查询条件使用 or 和 and 进行组合查询, 以后还会学到更加高级的条件查询方式, 这里不再多做介绍。
示例:
查询年龄在21岁以上的所有人信息: select * from students where age > 21;
查询名字中带有 "王" 字的所有人信息: select * from students where name like "%王%";
查询id小于5且年龄大于20的所有人信息: select * from students where id<5 and age>20;