[英]select only one row from multiple rows MySql
我有一個orders
表,如下所示:
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.獲取所有狀態至少為0的'cust_id'。
例如。 在上表中,我應該獲得帶有兩個行25和26的cust_id,因為它們在“狀態”列中至少有一個0。
2.獲取所有狀態為1的所有“ cust_id”。
例如。 在上表中,我應該獲得帶有一行27的cust_id,因為它在“狀態”列中全為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 )
這是兩個查詢..
如果您需要兩個結果都相同,則可以使用並集
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 )
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.