[英]MySQL - Select rows where column value is only 0, group by another column?
表格示例:
ID, foreign_id, status
ID
是唯一的 , foreign_id
不是。 示例行:
1, 1111, 0
2, 2222, 0
3, 3333, 1
4, 1111, 1
5, 4444, 0
我要選擇的是唯一的foreign_id
,其狀態僅為0。如果其狀態為0,但具有相同外部ID的另一行的狀態為1,請不要選擇該foreign_id
。 預期產量:
1, 2222, 0
5, 4444, 0
我可以選擇status = 0
並按foreign_id
分組,但是即使有另一行的foreign_id
和status與1相同,我也只會選擇status為0的行。
SELECT ID, foreign_id
FROM table
WHERE status = 0
GROUP BY foreign_id
任何幫助表示贊賞。
使用GROUP_CONCAT和DISTINCT
子句,我們組的所有對一個獨特的狀態foreign_id
。 現在在HAVING
子句中,我們只需要過濾掉僅當其唯一狀態為'0'
foreign_id
。
請嘗試以下操作:
SELECT ID, foreign_id, status, GROUP_CONCAT(DISTINCT status) as statuses
FROM table
GROUP BY foreign_id
HAVING statuses = '0'
您可以使用group by
並having
:
select foreign_id, max(status) as status
from t
group by foreign_id
having max(status) = 0;
基本上,您需要在group by
之后進行測試。
如果要完整的行,請使用not exists
:
select t.*
from t
where not exists (select 1
from t t2
where t2.foreign_id = t.foreign_id and t2.status <> 0
);
(我對此進行了編輯,以證明其有效並闡明了一些內容):
您可能感興趣的是HAVING語句。
您可以在 GROUP BY 之后使用HAVING語句。 這是一個很好的解釋: https : //www.dofactory.com/sql/having
簡而言之,HAVING語句的作用是讓您過濾作為GROUP BY表達式返回的數據。
嘗試這個:
SELECT
foreign_id, MAX(status) AS status
FROM
myTable
GROUP BY
foreign_id
HAVING
MAX(status) = 0
這是一個正常工作的示例(在基本的MS Access文件中測試):
如果您有任何疑問,請告訴我!
正如其他人所說,您應該匯總數據,但是與此同時存在很多潛在的問題。 但是在開始之前,您已經聲明要在輸出中顯示原始記錄,而不是合並數據,最簡單的解決方案是使用2個查詢-一個用於標識僅status = 0的foreign_id,另一個用於獲取對應的行
SELECT r.*
FROM examples r
JOIN ( SELECT s.foreign_id, MAX(s.status)
FROM examples s
GROUP BY s.foreign_id
HAVING MAX(s.status)=0
) t
ON r.foreign_id=t.foreign_id
或者,您可以獲取foreign_ids,其中status!= 0,並在第二個查詢中排除那些-這可能更有效,具體取決於數據的分布。
當“狀態” <0時,這種情況就不會解決。輸出將包括這些行(SUM()可能會發生相同的情況)。 有幾種解決方法,例如,可以使用SUM(ABS(status))或SUM(IF(status = 0,0,1))。 正如Madhur所建議的那樣,您也可以GROUP_CONCAT(status)並檢查列的輸出是否僅為'0'。
但是我懷疑您將要告訴我,狀態不能為負(或為null?),因為它是名義數字 。 如果是這種情況,則說明您使用了錯誤的數據類型-您應該使用ENUM。 如果真是這樣,則您不能將SUM()或MAX()應用於ENUM,但仍可以使用SUM(IF(status = ?, 0,1))或GROUP_CONCAT()方法。
因此....
SELECT r.*
FROM examples r
JOIN ( SELECT s.foreign_id, SUM(IF(status=0,0,1))
FROM examples s
GROUP BY s.foreign_id
HAVING SUM(IF(status=0,0,1))=0
) t
ON r.foreign_id=t.foreign_id
使用聚合函數
select * from t where foreign_id in (
select foreign_id
from t
group by foreign_id
having min(status) = 0
) and status!=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.