【发布时间】:2017-10-23 10:09:17
【问题描述】:
我正在编写一个用作数据库视图的查询,它现在看起来像这样
SELECT
contact.*,
contact_users.names AS user_names,
contact_status.status_id AS status_id,
status_translation.name AS status_name,
status_translation.lang_id AS lang_id
FROM contacts as contact
LEFT JOIN contact_status AS contact_status ON contact_status.status_id = contact.status
LEFT JOIN contact_status_translation AS status_translation ON status_translation.id = contact.status
LEFT JOIN (
SELECT
contacts_users.contact_id,
string_agg(users.fullname || ', ' || users.id, ' | ') as names
FROM v_contacts_users as contacts_users
LEFT JOIN v_users as users on users.id = contacts_users.user_id
WHERE users.lang_id = status_translation.lang_id
GROUP BY contacts_users.contact_id
) AS contact_users ON contact_users.contact_id = contact.id
WHERE contact.deleted = FALSE
除了最后一个LEFT JOIN 中的WHERE 条件外,一切都按预期工作-WHERE users.lang_id = status_translation.lang_id 部分表示status_translation 不能在查询的这一部分中引用?这是为什么?我试着用各种方法引用这个表,但结果还是一样。事情是v_users 也被翻译了,所以我只需要从这个表中得到一个结果。感谢您的任何提示
【问题讨论】:
-
在内联视图中将
where更改为and,你应该没问题。问题是在使用外连接时,左连接的左边只能有一个where子句,或者左连接产生的空记录被忽略;因为 NULL 是 到您的文本。 (不能以这种方式比较 null!)本质上,左连接变成了内连接。通过将 where 移动到连接条件,问题就消失了,因为在连接发生之前应用了过滤器,从而允许保留从连接创建的空记录。 -
如果您想使用子查询外部的一些值,请使用横向关键字。左连接横向(子查询)。从 9.3 开始,postgres 出现横向关键字。
标签: sql postgresql select join