[英]MySQL - get all unique values of a column, check if has a specific value
[英]Check column for unique value
我的桌子:
id attribute
1 2
1 2
2 3
2 4
5 1
5 1
6 3
6 3
6 5
現在我只想輸出帶attribute
id
,如果每個id
的屬性相同。
在此示例表中,輸出將是
id attribute
1 2
5 1
SELECT id, MIN(attribute) AS attribute
FROM test
GROUP BY id
HAVING COUNT(DISTINCT attribute) = 1 ;
要么:
SELECT id, MIN(attribute) AS attribute
FROM test
GROUP BY id
HAVING MIN(attribute) = MAX(attribute) ;
我期望最后一個版本在索引(id, attribute)
上非常有效
你可以使用這種方法:
SELECT DISTINCT id, attribute
FROM test t1
WHERE (SELECT count(DISTINCT attribute)
FROM test t2
WHERE t2.id = t1.id) = 1
更好的方法可能是:
SELECT
DISTINCT t1.id, t1.attribute
FROM
test t1,
(
SELECT
id,
count(DISTINCT attribute) COUNT
FROM
test
GROUP BY
id
HAVING
COUNT = 1
) t2
WHERE
t1.id = t2.id
好吧,我會使用以下方法:
SELECT DISTINCT ta.id, ta.attribute
FROM test ta
LEFT JOIN test tb
ON ta.id = tb.id AND ta.attribute <> tb.attribute
WHERE tb.id IS NULL;
...因為我通常傾向於至少嘗試用連接表替換嵌套查詢。 當然,如果你的桌子很小,那就不重要了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.