[英]SQL Select distinct column values
Lets say I have a MySQL table that has the following entries; 可以说我有一个包含以下条目的MySQL表;
ID, PRODUCTID
95, 2
95, 2
95, 1
96, 1
102, 1
102, 5
95, 5
How do I select the PRODUCTID(s) that only have one distinct ID-column value. 如何选择仅具有一个不同的ID列值的PRODUCTID。
The result I want to get back is: 我想得到的结果是:
PRODUCTID
2
I have tried something in the lines of; 我已经尝试了以下方法:
SELECT DISTINCT PRODUCTID
FROM `TABLE`
GROUP BY ID, PRODUCTID
HAVING COUNT(*) = 1;
Group by productid
and then use a count(distinct id)
to count unique id
s 按
productid
分组,然后使用count(distinct id)
对唯一id
进行计数
SELECT PRODUCTID
FROM your_table
GROUP BY PRODUCTID
HAVING COUNT(distinct ID) = 1
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;
COUNT(DISTINCT)
is one way to solve this problem. COUNT(DISTINCT)
是解决此问题的一种方法。 However, I prefer to compare MIN()
and MAX()
-- because these are cheaper to calculate: 但是,我更喜欢比较
MIN()
和MAX()
,因为计算起来比较便宜:
SELECT PRODUCTID
FROM `TABLE`
GROUP BY PRODUCTID
HAVING MIN(ID) = MAX(ID);
If ID
could be NULL
, you would need to add another condition: 如果
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
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.