使用单个查询选择使用三个表上的连接的记录数

时间:2017-02-15 16:09:32

标签: sql ruby-on-rails

我有群组模型,用户模型,故障单模型

分组has_many_and_belongs_to用户和用户has_many门票

**Groups**

id | name | user_id

**User**

id | name | group_id

**Ticket**

id | title | group_id | user_id

我想在

上检索属于特定群组的用户的门票数量

特定时间间隔

我尝试了这个,但没有奏效。

select t.user_id, t.group_id ,count(t.id), (select count(t.id)
from tickets t
where created_at < current_timestamp - INTERVAL '24 hours')
from tickets t
LEFT OUTER JOIN groups ON g.id=t.group_id
LEFT OUTER JOIN users u ON u.id=t.user_id 
GROUP BY t.user_id, t.group_id;

如何在单个查询中执行此操作?。

由于

1 个答案:

答案 0 :(得分:0)

如果您只想要user_id,group_id和cnt:

SELECT t.user_id, t.group_id , COUNT(t.id) cnt
FROM tickets t 
WHERE t.created_at < (current_timestamp - INTERVAL '24 hours')
GROUP BY t.user_id, t.group_id

如果您想查询和/或检索user_name:

SELECT t.user_id, t.group_id , COUNT(t.id)
FROM tickets t 
    INNER JOIN users u 
    ON u.id = t.user_id 
        AND u.name = 'USER_NAME'
WHERE t.created_at < (current_timestamp - INTERVAL '24 hours')
GROUP BY t.user_id, t.group_id

如果您想查询和/或检索group_name:

SELECT t.user_id, t.group_id , COUNT(t.id)
FROM tickets t 
    INNER JOIN groups g 
    ON g.id = t.group_id
        AND g.name = 'GROUP_NAME'
WHERE t.created_at < (current_timestamp - INTERVAL '24 hours')
GROUP BY t.user_id, t.group_id

如果要查询和/或检索user_name AND group_name:

SELECT t.user_id, t.group_id , COUNT(t.id)
FROM tickets t 
    INNER JOIN users u 
    ON u.id = t.user_id 
        AND u.name = 'USER_NAME'
    INNER JOIN groups g 
    ON g.id = t.group_id
        AND g.name = 'GROUP_NAME'
WHERE t.created_at < (current_timestamp - INTERVAL '24 hours')
GROUP BY t.user_id, t.group_id