2017-02-14 54 views
0

我有一個orders表如下:從多行僅選擇一個行的MySQL

id | cust_id| status 
1  25   1 
2  25   1 
3  25   0 
4  26   0 
5  26   1 
6  26   0 
7  27   1 
8  27   1 
9  27   1 

我需要兩個查詢:

1.獲取所有「的cust_id」具有至少一個狀態0

例如,在上面的表格中,我應該得到兩行25和26的cust_id,因爲他們在「狀態」欄至少有一個0。

2.取具有所有狀態爲1

例如所有的 '的cust_id'。在上面的表格中,我應該得到一行27的cust_id,因爲它在'status'列中有全部1。

+0

你能請分享你查詢你試試.... – Dani

+0

我已經提出了一個查詢,我認爲是正確的第一個條件。 – Francis

+0

SELECT * FROM'orders' where status = 0 group by cust_id – Francis

回答

0
SELECT DISTINCT cust_id FROM orders WHERE status=0 
UNION 
SELECT DISTINCT cust_id FROM orders WHERE status=1 
AND cust_id NOT IN (SELECT cust_id FROM orders WHERE status<>1) 
+0

您能否提供一些更多的細節,而不僅僅是SQL語句。謝謝。 –

1

假設狀態是數字

select distinct cust_id 
from my_table where status = 0 


select disctint cust_id 
from my_table 
where cust_id NOT in (select distinct cust_id 
from my_table where status = 0) 

這是兩個查詢..

如果你需要兩個結果相同的選擇,你可以使用union

select distinct cust_id 
from my_table where status = 0 
union 
select disctint cust_id 
from my_table 
where cust_id NOT in (select distinct cust_id 
from my_table where status = 0) 
+0

@RomanPerekhrest非常感謝.. – scaisEdge

+0

不客氣... – RomanPerekhrest

+0

爲什麼downvote沒有任何動機? – scaisEdge