postgres JOIN左表null

时间:2017-09-26 15:22:14

标签: postgresql join null

我的查询是:

SELECT main.group_id, s_ref.title, s_ref.username, main.m_per_group, main.pos, u.lang 
FROM (
    SELECT user_id, group_id, COUNT(user_id) AS m_per_group,
        ROW_NUMBER() OVER (
            PARTITION BY group_id
            ORDER BY COUNT(group_id) DESC
            ) AS pos 
    FROM messages
    WHERE message_date > date_trunc('week', now())
    GROUP BY group_id, user_id
) AS main 
LEFT OUTER JOIN supergroups_ref AS s_ref
USING (group_id)
RIGHT JOIN users AS u
ON u.user_id = main.user_id
WHERE main.user_id = %s
ORDER BY m_per_group DESC

问题是当main返回0个元素时,我既没有得到用户JOIN用户的语言,也没有得到[]

我想获得[(None, None, None, None, 'en')]这就是我使用正确联接的原因。我怎样才能得到我想要的结果?

1 个答案:

答案 0 :(得分:0)

移动此条件:

WHERE main.user_id = %s

到主子查询:

WHERE message_date > date_trunc('week', now()) and main.user_id = %s

现在的方式是将外连接转换为内连接。