從不訂購的客戶

2021-10-24 13:15:27 字數 2099 閱讀 5348

create

table

ifnot

exists customers (id int

, name varchar

(255))

create

table

ifnot

exists orders (id int

, customerid int

)truncate

table customers

insert

into customers (id, name)

values

('1'

,'joe'

)insert

into customers (id, name)

values

('2'

,'henry'

)insert

into customers (id, name)

values

('3'

,'sam'

)insert

into customers (id, name)

values

('4'

,'max'

)truncate

table orders

insert

into orders (id, customerid)

values

('1'

,'3'

)insert

into orders (id, customerid)

values

('2'

,'1'

)

某**包含兩個表,customers 表和 orders 表。編寫乙個 sql 查詢,找出所有從不訂購任何東西的客戶。

customers 表:

±—±------+

| id | name |

±—±------+

| 1 | joe |

| 2 | henry |

| 3 | sam |

| 4 | max |

±—±------+

orders 表:

±—±-----------+

| id | customerid |

±—±-----------+

| 1 | 3 |

| 2 | 1 |

±—±-----------+

例如給定上述**,你的查詢應返回:

±----------+

| customers |

±----------+

| henry |

| max |

±----------+

方法:使用子查詢和not in子句

如果我們有乙份曾經訂購過的客戶名單,就很容易知道誰從未訂購過。

我們可以使用下面的**來獲得這樣的列表。

select customerid from orders;
然後,我們可以使用 not in 查詢不在此列表中的客戶。

select customers.name as

'customers'

from customers

where customers.id notin(

select customerid from orders

);

方法:關聯查詢

select t1.name customers 

from customers t1

left

join orders t2 on t1.id = t2.customerid

where t2.customerid is

null

select t1.name customers 

from customers t1

left

join orders t2 on t1.id = t2.customerid

where t2.customerid is

null

從不訂購的客戶

假設乙個 包含兩個表,customers表和orders表。編寫乙個sql語句找出所有從不訂購任何東西的客戶。customers表 id name 1 joe 2 henry 3 sam 4 max orders表 id customerid 1 3 2 1 以上述 為例,返回以下內容 custom...

從不訂購的客戶

題目 從不訂單的客戶 某 包含兩個表,customers 表和 orders 表。編寫乙個 sql 查詢,找出所有從不訂購任何東西的客戶。customers 表 id name 1 joe 2 henry 3 sam 4 max orders 表 id customerid 1 3 2 1 例如給定...

從不訂購的客戶

sql架構 某 包含兩個表,customers 表和 orders 表。編寫乙個 sql 查詢,找出所有從不訂購任何東西的客戶。customers 表 id name 1 joe 2 henry 3 sam 4 max orders 表 id customerid 1 3 2 1 例如給定上述 你的...