计算来自多个表的关联

时间:2016-06-30 10:04:16

标签: sql postgresql

我想知道给定表中每个记录的关联数量。其中一些关联附加了一些条件

到目前为止我已经

-- Count app associations
SELECT 
distinct a.name, 
COALESCE(v.count, 0) as visitors, 
COALESCE(am.count, 0) AS auto_messages,
COALESCE(c.count, 0) AS conversations
FROM apps a
LEFT JOIN (SELECT app_id, count(*) AS count FROM visitors GROUP BY 1) v ON a.id = v.app_id
LEFT JOIN (SELECT app_id, count(*) AS count FROM auto_messages GROUP BY 1) am ON a.id = am.app_id
LEFT JOIN (
    SELECT DISTINCT c.id, app_id, count(c) AS count 
    FROM conversations c LEFT JOIN messages m ON m.conversation_id = c.id
    WHERE m.visitor_id IS NOT NULL
    GROUP BY c.id) c ON a.id = c.app_id
WHERE a.test = false
ORDER BY visitors DESC;

我遇到了对话的最后一个连接语句的问题。我想计算至少有一条消息的会话数,其中visitor_id不为null。出于某种原因,我为每个应用程序获得了多条记录,即。对话没有正确分组。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我的直觉,基于对大图的有限理解:在conversations选择的嵌套查询中,

  • 删除DISTINCT
  • 从SELECT list
  • 中删除c.id
  • GROUP BY c.app_id而不是c.id

编辑:试试这个

...
LEFT JOIN (
    SELECT app_id, count(*) AS count 
    FROM conversations c1
    WHERE 
    EXISTS (
        SELECT *
        FROM messages m
        WHERE m.conversation_id = c1.id and
            M.visitor_id IS NOT NULL
    )
    GROUP BY c1.app_id) c
ON a.id = c.app_id