leetcode -database- 183. Customers who never order

      
      Original question: https://leetcode-cn.com/problems/customers-who-never-order/
      I made the problem-solving record for the database problem of leetcode:
              Problem-solving directory https://blog.csdn.net/weixin_42845682/ article / details / 105196004
      
      

Title description:

      A website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+ 

      Orders table:

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+ 

      For example, given the above table, your query should return:

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+ 

      

answer:

The first answer

      I think this question is very simple, nothing to do. . .

select 
    name customers 
from Customers
where id not in
(
	select
	    distinct(c.id) 
	from Customers c 
	join orders o on c.id=o.Customerid 
) 

The second answer

      Take a look at the table structure, I feel that it is not so troublesome ...

select 
    name customers 
from Customers
where id not in
(
select
    distinct(CustomerId) 
from Orders  
) 

The third answer

      The first two methods are to seek union and then do not exist. You can also find the difference set and then exist (however, I remember there is no difference set in mysql, so I used oracle):


SELECT
    name customers 
    from
    customers c 
where id in
    (
		SELECT id FROM Customers 
		minus 
		SELECT distinct(customerid) FROM Orders 
    ) 

      But this way of writing seems to be very slow to execute, and leetcode shows 1914 ms. I don't know if it's a problem with leetcode or my writing is wrong.

The fourth answer

      Actually, this problem can be done with join. If you do n’t understand, I recommend this:
Use join to achieve the intersection, union, difference, and complement effects
https://blog.csdn.net/weixin_42845682/article/details/105414734

select
    distinct(c.name) customers 
from customers c 
left join orders o on c.id = o.customerid 
where o.id is null

      But, I can't figure it out, why did I report it wrong when I added distinct. . . But it's not a big mistake, this is based on business needs, maybe people have changed their names.
      So the correct answer is:

select
    c.name customers 
from customers c 
left join orders o on c.id = o.customerid 
where o.id is null

      
      
      
      
      

Published 48 original articles · Like 36 · Visits 130,000+

Guess you like

Origin blog.csdn.net/weixin_42845682/article/details/105412597