我有一个表订单:
|--------------------|-----------------|------------|
| user_id | article_id | Name |
|--------------------|-----------------|------------|
| 1 | 39 | John |
| 1 | 39 | John |
| 2 | 39 | Mike |
| 2 | 19 | Mike |
| 3 | 39 | Dave |
|--------------------|-----------------|------------|
我怎样才能只选择那些 article_id = 39 的用户,不管有多少次,但如果它只出现一次。 我需要选择用户 John 和用户 Dave,而不是 Mike。 Mike 的 article_id 为 39,但他的 article_id = 19。 该查询应返回用户 John 和 Dave。
我试过这个查询:
SELECT * FROM orders AS o where o.article_id = 39
GROUP BY o.user_id HAVING COUNT(o.article_id) > 0
但它返回所有三个用户。我不需要用户 Mike。
最佳答案
在 HAVING
子句中使用条件聚合:
SELECT user_id, Name
FROM orders
GROUP BY user_id, Name
HAVING SUM(CASE WHEN article_id <> 39 THEN 1 ELSE 0 END) = 0;
注意:您的表未规范化,用户信息属于单独的用户表。我可以通过在 GROUP BY
子句中包含名称来解决这个问题,但我们应该按 user_id
进行聚合。
关于mysql - 从表中选择用户一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48638272/