繁体   English   中英

根据具体情况加入3个表

[英]Joining 3 Tables based on specific conditions

我有以下3个表格:

  • 用户:[id,name,admin ...]
  • 事件:[id,user_id,type ...]
  • 消息:[id,user_id,...]

我想构建一个执行以下操作的查询:

- >从未安排“集合” 类型 事件的表用户中选择所有用户

- >并且少于3 “collection_reminder” 类型的 消息

- >谁不是管理员

我已经设法弄清楚了这个查询的第一部分,但是当我尝试添加3个表,进行计数等时,它都变得有点像梨形。

这是一个可能完成工作的查询。 每个需求都表示为WHERE子句中的条件,在需要时使用相关子查询:

SELECT u.*
FROM users u
WHERE 
    NOT EXISTS (
        SELECT 1 
        FROM events e 
        WHERE e.user_id = u.id AND e.type = 'collection'
    )
    AND (
        SELECT COUNT(*) 
        FROM messages m 
        WHERE m.userid = u.id AND m.type = 'collection_reminder'
    ) <= 3
    AND u.admin IS NULL

我试试这个在头顶,所以期待一些synthax问题,但想法如下。

您可以使用左连接过滤掉没有事件计划的人员。 在左边连接上,查询第二部分上的元素将显示为null。

select * from users u
left join events e on e.user_id = u.id
where e.user_id is null

现在,我不认为这是最高效的方式,而是一种搜索包含3个或更少消息的每个人的简单方法:

select * from users u
left join events e on e.user_id = u.id
where u.id in (
   select COUNT(*) from messages m where m.user_id = u.id HAVING COUNT(*)>3;
)
and e.user_id is null

然后过滤谁不是管理员是最简单的:D

select * from users u
left join events e on e.user_id = u.id
where u.id in (
   select COUNT(*) from messages m where m.user_id = u.id HAVING COUNT(*)>3;
)
and e.user_id is null
and u.admin = false

希望能帮助到你。

这几乎是您的要求的直接翻译,按您列出的顺序:

SELECT u.*
FROM users AS u
WHERE u.user_id NOT IN (SELECT user_id FROM events WHERE event_type = 'Collection')
   AND u.user_id IN (
      SELECT user_id 
      FROM messages 
      WHERE msg_type = 'Collection Reminder' 
      GROUP BY user_id 
      HAVING COUNT(*) < 3
   )
   AND u.admin = 0

或者,这可以通过连接完全实现:

SELECT u.*
FROM users AS u
LEFT JOIN events AS e ON u.user_id = e.user_id AND e.event_type = 'Collection'
LEFT JOIN messages AS m ON u.user_id = m.user_id AND m.msg_type = 'Collection Reminder'
WHERE u.admin = 0
   AND e.event_id IS NULL        -- No event of type collection
GROUP BY u.user_id -- Note: you should group on all selected fields, and 
                   -- some configuration of MySQL will require you do so.
HAVING COUNT(DISTINCT m.message_id) < 3   -- Less than 3 collection reminder messages 
             -- distinct is optional, but 
             -- if you were to remove the "no event" condition, 
             -- multiple events could multiply the message count.
;

此查询使用连接来链接3个表,使用where子句过滤结果,并使用Group by,将结果限制为仅满足小于计数条件的那些。

SELECT    a.id, 
      SUM(CASE WHEN b.type = 'collection' THEN 1 ELSE 0 END),
      SUM(CASE WHEN c.type = 'collection_reminder' THEN 1 ELSE 0 END
FROM      users a 
left join   events b on (b.user_id = a.id)
left join   messages c on (c.user_id = a.id)
WHERE     a.admin = false
GROUP BY  a.id
HAVING  SUM(CASE WHEN b.type = 'collection' THEN 1 ELSE 0 END) = 0 
    AND SUM(CASE WHEN c.type = 'collection_reminder' THEN 1 ELSE 0 END) < 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM