MySQL 只选择唯一值

时间:2021-02-04 11:58:33

标签: mysql sql

我有两张桌子。

客户:

+--------------+-------------+
|   CLIENT_ID  |    LABEL    |
+--------------+-------------+
|          123 |      label1 |
+--------------+-------------+
|          123 |      label3 |
+--------------+-------------+
|          456 |      label1 |
+--------------+-------------+
|          789 |      label2 |
+--------------+-------------+
|          987 |      label2 |
+--------------+-------------+
|          987 |      label4 |
+--------------+-------------+

经理:

+----+--------------+
| ID |   CLIENT_ID  |
+----+--------------+
|  1 |          123 |
+----+--------------+
|  1 |          456 |
+----+--------------+
|  2 |          456 |
+----+--------------+
|  3 |          789 |
+----+--------------+
|  3 |          987 |
+----+--------------+
|  4 |          789 |
+----+--------------+

我需要从只有带有标签“label1”或“label2”的客户且没有带有其他标签的客户的 Managers 中选择 ID。 结果输出应该像 2 和 4。

我试着这样做

select m.id
from managers m
    join clients c on m.client_id = c.client_id
where c.label in ('label1', 'label2');

但它返回所有 ID。

5 个答案:

答案 0 :(得分:0)

关闭。只需添加聚合:

select m.id
from managers s join
     clients c
     on m.client_id = c.client_id
where c.label in ('label1', 'label2')
group by m.id
having count(distinct c.label) = 2;

如果您希望客户端具有这两个标签,请使用:

select m.id
from managers s join
     clients c
     on m.client_id = c.client_id
group by m.id
having count(distinct c.label) = 2;

select m.id
from managers s join
     clients c
     on m.client_id = c.client_id
group by m.id
having count(distinct case when c.label in ('label1', 'label2') then c.label end) = 2 and
       count(distinct c.label) = 2;

或者,更有效:

having sum(c.label = 'label1') > 0 and
       sum(c.label = 'label2') > 0 and
       sum(c.label not in ('label1', 'label2')) = 0;

答案 1 :(得分:0)

使用 group by 如下:

select m.id
from managers m
    join clients c on m.client_id = c.client_id
where c.label in ('label1', 'label2')
group by m.id
having count(*) = 1;

答案 2 :(得分:0)

请在此处尝试使用 group byhaving 语句以获取唯一记录

 SELECT ID FROM `Clients` c 
  left join Managers m on (c.client_id = m.CLIENT_ID) 
  where LABEL in ('label1', 'label2') 
  group by ID having count(*) = 1

谢谢

答案 3 :(得分:0)

您可以使用 CTE 获取与特定经理关联的客户标签有效的出现次数:

with r as (select m.id id, sum(c.label in ('label1', 'label2')) c1, count(*) c2 
           from managers m join clients c on m.client_id = c.client_id group by m.id)
select id from r where c1 = c2;

输出:

<头>
id
2
4

答案 4 :(得分:0)

加入表,按经理分组,并在 HAVING 子句中为您的条件使用条件聚合:

SELECT m.id
FROM managers m INNER JOIN clients c 
ON m.client_id = c.client_id
GROUP BY m.id
HAVING MAX(c.label IN ('label1', 'label2')) = 1
   AND MAX(c.label NOT IN ('label1', 'label2')) = 0

如果客户端同时具有 'label1''label2' 标签并且可以扩展到更多标签,这也将起作用。

参见demo
结果:

<头>
id
2
4