我还在做我的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秒)/但我确定那些存在;
答案 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 );