Mysql通过多个列值连接和过滤

时间:2017-04-18 21:22:55

标签: mysql sql join group-by

我有以下查询

select events.* from clients
inner join events on events.client_id = clients.id
inner join salons on clients.business_id = businesses.id
where businesses.campaign_id = 27

产生

id  client_id   category
3605    608     0
3606    608     1
3607    608     2
3608    608     3
3611    609     0
3612    609     1
3613    609     2
3614    609     3
3615    609     5
3616    609     6
3617    610     0
3618    610     1
3619    610     2
3620    610     3
3621    610     5
3622    610     6

我需要选择所有类别为0,1,2或3但不属于类别4,5或6的客户。

我认为可能有一种方法可以将事件行组合在一起,而不会失去对所有类别数据的访问权。

因此,使用上述数据,所需的结果将是:

id  client_id   category
3605    608     0
3606    608     1
3607    608     2
3608    608     3

最终,我只对那些有某些事件而非其他事件的客户感兴趣,因此client_id为609和610的结果将被省略,因为它们包含0,1,2或3类而不是4,5类,或者6。

3 个答案:

答案 0 :(得分:1)

从您的示例数据中,我假设该类别可以采用0..6之间的值。鉴于此,您可以按client_id进行分组,并仅接受max(category) <= 3;这可以确保4..6之间没有类别,1..3之间至少有一个类别。

select events.client_id from clients
inner join events on events.client_id = clients.id
inner join salons on clients.business_id = businesses.id
where businesses.campaign_id = 27
group by client_id
having max(category)<=3

如果您还想要保留事件数据&#34;,您可以将上述查询用作子查询:

select events.* from clients
inner join events on events.client_id = clients.id
inner join salons on clients.business_id = businesses.id
where businesses.campaign_id = 27
      and events.clients.id in (
    select events.client_id from clients
    inner join events on events.client_id = clients.id
    inner join salons on clients.business_id = businesses.id
    where businesses.campaign_id = 27
    group by client_id
    having max(category)<=3
)

答案 1 :(得分:0)

select events.* from clients
inner join events on events.client_id = clients.id
inner join salons on clients.business_id = businesses.id
where businesses.campaign_id = 27
and events.categoryid in (0,1,2,3)
and not exists 
(select * from events x 
 where x.client_id = clients.id and events.categoryid in (4,5,6)
)

答案 2 :(得分:-1)

select clients.id from clients
inner join events on events.client_id = clients.id
inner join salons on clients.business_id = businesses.id
where businesses.campaign_id = 27
group by clients.id
having SUM( CASE WHEN category in ( 0,1,2,3) THEN 1 ELSE 0 END ) = 4;