AND 和 OR 也叫连接运算符,在查询数据时用于缩小查询范围,我们可以用 AND 或者 OR 指定一个或多个查询条件。

1.AND

AND 运算符表示一个或者多个条件必须同时成立,结合WHERE子句使用。

1.1语法

  1. SELECT column1, column2, columnN
  2. FROM table_name
  3. WHERE [condition1] AND [condition2]...AND [conditionN];

1.2示例

company表中内容如下:

runoobdb=# select * from company;
 id | name  | age |                      address                       | salary
----+-------+-----+----------------------------------------------------+--------
  1 | Paul  |  32 | California                                         |  20000
  2 | Allen |  25 | Texas                                              |  15000
  3 | Teddy |  23 | Norway                                             |  20000
  4 | Mark  |  25 | Rich-Mond                                          |  65000
  5 | David |  27 | Texas                                              |  85000
  6 | Kim   |  22 | South-Hall                                         |  45000
  7 | James |  24 | Houston                                            |  10000
(7 行记录)

查询年龄小于等于25,且薪资大于65000的人有哪些:

runoobdb=# SELECT * FROM COMPANY WHERE AGE <= 25 AND SALARY >= 65000;
 id | name | age |                      address                       | salary
----+------+-----+----------------------------------------------------+--------
  4 | Mark |  25 | Rich-Mond                                          |  65000
(1 行记录)

2.OR

OR运算符表示多个条件中只需要满足其中任意一个即可。

2.1语法

SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]

2.2示例

依然以company表做测试
查询年龄小于23的或者薪资大于80000的;

runoobdb=# SELECT * FROM COMPANY WHERE AGE < 23 OR SALARY > 80000;
 id | name  | age |                      address                       | salary
----+-------+-----+----------------------------------------------------+--------
  5 | David |  27 | Texas                                              |  85000
  6 | Kim   |  22 | South-Hall                                         |  45000
(2 行记录)