MySQL查询不返回所需的结果。没有任何订单的客户不会显示

时间:2016-12-26 03:58:39

标签: mysql sql

我还在做我的SQL培训。所以我有两个表CUSTOMERS和ORDERS(外键表)。现在我需要让所有客户都没有任何订单。这是我的查询

select LASTNAME, FIRSTNAME 
  from CUSTOMERS 
  WHERE CUSTOMERS.ID NOT IN 
      (select ID_CUSTOMER from ORDERS);

+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| ID        | int(11)      | NO   | PRI | NULL    |       |
| FIRSTNAME | varchar(50)  | YES  |     | NULL    |       |
| LASTNAME  | varchar(50)  | YES  |     | NULL    |       |
| ADDRESS   | varchar(100) | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+


+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| ID            | int(11)      | NO   | PRI | NULL    |       |
| PRODUCT_NAME  | varchar(100) | YES  |     | NULL    |       |
| PRODUCT_PRICE | double(10,4) | YES  |     | NULL    |       |
| DATE_ORDER    | date         | YES  |     | NULL    |       |
| ID_CUSTOMER   | int(11)      | YES  |     | NULL    |       |
| AMOUNT        | int(11)      | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+

但我收到空集(0,00秒)/但我确定那些存在;

1 个答案:

答案 0 :(得分:4)

我怀疑NULL表的ID_CUSTOMER列中有一些ORDERS值。当子查询中存在NOT IN值时,NULL会失败。

使用NOT EXISTS

select LASTNAME, FIRSTNAME 
  from CUSTOMERS C
  WHERE NOT EXISTS (select ID_CUSTOMER from ORDERS O Where C.ID = O.ID_CUSTOMER );