3.3.4.2 选择指定的行

像在前一章展示的,提取全部的表是很容易的。从SELECT语句中忽略WHERE语句。但通常你不想查看全部的表,特别是它变得很大时。相反,通常你会查询一些特别的问题,在这种情况下你会对信息作一些限制。让我们看一些查询问题。

你可以仅指定一些特别的行从你的表中。例如,你想核对你更改的Bowser的出生日期,像这样查询Bowser的记录:

mysql> select * from pet where name = "Bowser";
+--------+-------+---------+------+------------+------------+
| name   | owner | species | sex  | birth      | death      |
+--------+-------+---------+------+------------+------------+
| Bowser | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
+--------+-------+---------+------+------------+------------+

输出确定了年份是正确的1989,而不是1979.

字符串的比较通常是大小写不敏感的,因此你可以指定名字"bowser", “BOWSER"等。查询的结果是一样的。

你可以在任何列指定条件,而不仅在name上。例如,你想知道哪些动物出生于1998或1998之后,测试birth列:

mysql> select * from pet where birth >= "1998-01-01";
+----------+-------+---------+------+------------+-------+
| name     | owner | species | sex  | birth      | death |
+----------+-------+---------+------+------------+-------+
| Chirpy   | Gwen  | bird    | f    | 1998-09-11 | NULL  |
| Puffball | Diane | hamster | f    | 1999-03-30 | NULL  |
+----------+-------+---------+------+------------+-------+

你可以把条件结合起来,例如,定位母狗:

mysql> select * from pet where species="dog" AND sex = 'f';
+-------+--------+---------+------+------------+-------+
| name  | owner  | species | sex  | birth      | death |
+-------+--------+---------+------+------------+-------+
| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |
+-------+--------+---------+------+------------+-------+

上一条查询使用了AND逻辑操作符。这里也有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  |
| Slim   | Benny | snake   | m    | 1996-04-29 | NULL  |
+--------+-------+---------+------+------------+-------+

AND 和 OR可以混合使用,尽管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  |
+-------+--------+---------+------+------------+-------+

results matching ""

    No results matching ""