假设我有一个MySQL表,其中包含以下条目;
ID, PRODUCTID
95, 2
95, 2
95, 1
96, 1
102, 1
102, 5
95, 5
如何选择仅具有一个不同ID列值的PRODUCTID。
我想要回来的结果是:
PRODUCTID
2
我尝试了一些方法;
SELECT DISTINCT PRODUCTID
FROM `TABLE`
GROUP BY ID, PRODUCTID
HAVING COUNT(*) = 1;
答案 0 :(得分:2)
按productid
分组,然后使用count(distinct id)
计算唯一的id
SELECT PRODUCTID
FROM your_table
GROUP BY PRODUCTID
HAVING COUNT(distinct ID) = 1
答案 1 :(得分:2)
SELECT DISTINCT x.PRODUCTID
FROM my_table x
LEFT
JOIN my_table y
ON y.PRODUCTID = x.PRODUCTID
AND y.ID <> x.ID
WHERE y.ID IS NULL;
答案 2 :(得分:2)
COUNT(DISTINCT)
是解决此问题的一种方法。但是,我更愿意比较MIN()
和MAX()
- 因为这些计算成本更低:
SELECT PRODUCTID
FROM `TABLE`
GROUP BY PRODUCTID
HAVING MIN(ID) = MAX(ID);
如果ID
可能是NULL
,则需要添加其他条件:
SELECT PRODUCTID
FROM `TABLE`
GROUP BY PRODUCTID
HAVING (MIN(ID) = MAX(ID) AND COUNT(*) = COUNT(ID)) OR -- No NULL values
(MIN(ID) IS NULL); -- or all NULL values
答案 3 :(得分:-1)
ID, PRODUCTID
95, 2
95, 2
95, 1
96, 1
102, 1
102, 5
95, 5
you can use this this is working fine
SELECT distinct product_id from category GROUP BY id, product_id
HAVING COUNT(*) = 1;