MySQL 8.4 Release Notes
5.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年后,测试birth
列:
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 |
+----------+-------+---------+------+------------+-------+
你可以组合条件,例如,找到母狗:
mysql> SELECT * FROM pet WHERE species = 'dog' AND sex = 'f';
+-------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+-------+--------+---------+------+------------+-------+
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+-------+--------+---------+------+------------+-------+
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 |
+----------+-------+---------+------+------------+-------+
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 |
+-------+--------+---------+------+------------+-------+