MySQL使用WHERE命令来限定数据查询条件。
语法:SELECT 属性1,属性2 FROM 表名 WHERE 条件1 OR 条件2 AND 条件3
说明:WHERE同样适用于UPDATE、DELETE等命令;
使用OR、AND实现多限制条件下的数据查询;
where执行顺序是从左往右执行的,在数据量小的时候不用考虑,但数据量多的时候要考虑条件的先后顺序,此时应遵守一个原则:排除越多的条件放在第一个;
使用主键作为查询的限定条件,速度是非常快的。
操作符说明表(A=10,B=20)
操作符 | 描述 | 示例说明 |
= | 等号,检测两个值是否相等,若相等,则返回True | (A = B)返回False |
<>,!= | 不等于,检测两个值是否相等,若不相等,则返回True | (A != B)返回True |
> | 大于,检测左边的值是否大于右边的值,若左边的值大于右边的值,则返回True | (A > B)返回False |
< | 小于,检测左边的值是否小于右边的值,若左边的值小于右边的值,则返回True | (A < B)返回True |
>= | 不小于,检测左边的值是否不小于右边的值,若左边的值不小于右边的值,则返回True | (A >= B)返回False |
<= | 不大于,检测左边的值是否不大于右边的值,若左边的值不大于右边的值,则返回True | (A <= B)返回True |
BETWEEN....AND.... | 介于指定范围之内 | where num between 3 and 5 |
NOT BETWEEN...AND... | 不在限定的范围内 | where num not between 3 and 5 |
IN(项1,项2,项3...) | 值在指定项内 | where num in (3,5,6) |
NOT IN(项1,项2,项3...) | 值不在指定项内 | where num not in (3,5,6) |
IS NULL | 空值判断符 | where name is null |
IS NOT NULL | 非空值判断符 | where name is not null |
NOT、AND、OR | 取反,与,或,优先级NOT>AND>OR,用于多个逻辑连接 | where num>2 AND num<6 |
LIKE | 搜索匹配,常与模式匹配符配合使用 | —— |
NOT LIKE | LIKE的反义 | —— |
% | 模式匹配符,表示任意字符串 | where username like ‘%user‘ |
若A或B的值为字符型,需要加上" "或‘ ‘。
默认情况下,where语句是不区分字母大小写的,需要通过BINARY强制区分。
示例:
mysql> select num,name from courses where name=.‘语文‘;
+-----+--------+
| num | name |
+-----+--------+
| 2 | 语文 |
+-----+--------+
mysql> SELECT * from tutorials_tbl WHERE tutorial_author=‘Sanjay‘;
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
| 6 | JAVA Tutorial | SANJAY | 2007-05-26 |
+-------------+----------------+-----------------+-----------------+
1 rows in set (0.01 sec)
mysql> SELECT * from tutorials_tbl WHERE BINARY tutorial_author=‘Sanjay‘; //强制区分大小写
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
mysql> select num,name from courses where num>2 AND num<5;
+-----+--------+
| num | name |
+-----+--------+
| 3 | 英语 |
| 4 | 化学 |
+-----+--------+
2 rows in set (0.00 sec)
mysql> select num,name from courses where NOT num>2;
+-----+--------+
| num | name |
+-----+--------+
| 1 | 数学 |
| 2 | 语文 |
+-----+--------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM courses WHERE name LIKE ‘%文‘;
+-----+--------+-----------------+
| num | name | submission_date |
+-----+--------+-----------------+
| 2 | 语文 | 2018-01-30 |
+-----+--------+-----------------+
1 row in set (0.00 sec)