簡體   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