+-------------+---------+ |Column Name | Type | +-------------+---------+ | id |int| | name |varchar| +-------------+---------+ id 是这个表的主键。 表的每一行表示一个用户的ID和名字
表:Orders
1 2 3 4 5 6 7 8 9
+-------------+------+ |Column Name | Type | +-------------+------+ | id |int| | customerId |int| +-------------+------+ id 是这个表的主键。 customerId是来自Customers表的外键 表的每一行表示一个订单的ID以及下订单的用户的ID
输入: Customers 表: +----+-------+ | id | name | +----+-------+ |1| Joe | |2| Henry | |3| Sam | |4| Max | +----+-------+ Orders 表: +----+------------+ | id | customerId | +----+------------+ |1|3| |2|1| +----+------------+
输出: +-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
解法1:
1 2 3 4
SELECT c.Name AS Customers FROM Customers c LEFTJOIN Orders o ON c.Id=o.CustomerId WHERE o.CustomerId ISNULL
解法2:
1 2 3 4 5 6 7
SELECT a.Name AS Customers FROM Customers AS a WHERENOTEXISTS( SELECT* FROM Orders AS b WHERE a.Id = b.CustomerId );