1.3.4.2 检索部分数据行
在上一小节中,我们很容易检索到表中的所有数据,在 SELECT 语句中省略了 WHERE ,但是,当表变的很庞大,或者是您只想看想要的数据,此时需要加上 WHERE 条件,下面让我们看看一些关于宠物的选择查询。
从表中选择特定的行
例如:您想验证下对 Bowser 的出生日期更改是否生效,那么您可以这样选择 Bowser 的记录:
mysql> SELECT * FROM pet WHERE name = 'Bowser';
+--------+-------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+--------+-------+---------+------+------------+------------+
| Bowser | Diane | dog | m | 1989-08-30 | 1995-07-29 |
+--------+-------+---------+------+------------+------------+
1 row in set (0.00 sec)
这个结果中显示 birth 已经更改为 1989,而非 1979。
Tips
字符串的比较是不区分大小写的,这点需要尤其注意,如上面的例子中 将 Bowser 更改成 bowser、BOWSER都可以得到相同的结果。
Note
在 SQL 的语句中,如果字符串的比较需要区分大小写,那么,有两种做法,一是在 SQL 语句中增加 binary 关键字,例如:
SELECT * FROM pet WHERE binary name = 'BowsEr';
或SELECT * FROM pet WHERE name = binary 'Bowser';
只是关键字 binary 的位置不同,但效果相同。另一种做法是:将 pet 表中 name 子段的数据类型由 varchar 更改成 binary、varbinary即可。
范围检索
例如:检索 1998 之后出生的宠物。
mysql> SELECT * FROM pet WHERE birth >= '1998-1-1';
+----------------------+-------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+----------------------+-------+---------+------+------------+-------+
| Chirpy | Gwen | bird | f | 1998-09-11 | NULL |
| Puffball | Diane | hamster | f | 1999-03-30 | NULL |
+----------------------+-------+---------+------+------------+-------+
2 rows in set (0.00 sec)
多条件检索 AND
mysql> SELECT * FROM pet WHERE species = 'dog' AND sex = 'f';
+----------------------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+----------------------+--------+---------+------+------------+-------+
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+----------------------+--------+---------+------+------------+-------+
1 row in set (0.00 sec)
多条件检索 OR
mysql> SELECT * FROM pet WHERE species = 'snake' OR species = 'bird';
+----------------------+-------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+----------------------+-------+---------+------+------------+-------+
| Chirpy | Gwen | bird | f | 1998-09-11 | NULL |
| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL |
| Slim | Benny | snake | m | 1996-04-29 | NULL |
+----------------------+-------+---------+------+------------+-------+
3 rows in set (0.00 sec)
AND 和 OR 并存
mysql> SELECT * FROM pet WHERE (species = 'cat' AND sex = 'm')
-> OR (species = 'dog' AND sex = 'f');
+----------------------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+----------------------+--------+---------+------+------------+-------+
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+----------------------+--------+---------+------+------------+-------+
2 rows in set (0.00 sec)