PostgreSQL同表左外连接多表

Posted

技术标签:

【中文标题】PostgreSQL同表左外连接多表【英文标题】:PostgreSQL Same Table Left Outer Join With Multiple Tables 【发布时间】:2013-12-31 14:27:07 【问题描述】:

我有一张表需要与两个不同的表进行左外连接。当我将表两次放入查询中并在 where 子句中将其与自身连接时(如下面的句子),它可以工作。我认为这不应该是正确的方法。如何编写 select 语句并将表与多个不同的表进行外连接?

SELECT cols."COLUMN_NAME"
     , COALESCE(translations."COLUMN_LANG_TITLE",cols."COLUMN_TITLE") AS "COLUMN_TITLE" 
     , options."OPTION_DESC"
  FROM 

"EXTAPP_SETUP"."OBJECT_COLUMNS_TAB" cols LEFT OUTER JOIN "EXTAPP_SETUP"."COLUMN_LANG_TITLES_TAB" translations
        ON translations."EXTAPP_ID" = cols."EXTAPP_ID" and translations."OBJECT_NAME" = cols."OBJECT_NAME" and translations."COLUMN_NAME" = cols."COLUMN_NAME" and translations."LANGUAGE_CODE" = 'fr',

"EXTAPP_SETUP"."OBJECT_COLUMNS_TAB" cols2 LEFT OUTER JOIN "EXTAPP_SETUP"."COL_FIX_OPTIONS_TAB" options
        ON options."EXTAPP_ID" = cols2."EXTAPP_ID" and options."OBJECT_NAME" = cols2."OBJECT_NAME" and options."COLUMN_NAME" = cols2."COLUMN_NAME" 

WHERE cols."EXTAPP_ID" = cols2."EXTAPP_ID" and cols."OBJECT_NAME" = cols2."OBJECT_NAME" and cols."COLUMN_NAME" = cols2."COLUMN_NAME" 

【问题讨论】:

【参考方案1】:

您可以使用后续的左连接。 由于您并没有真正使用 cols2 表,因此您可以从查询中消除它。这也将消除 where 子句,因为您不需要将 cols 表与其自身连接

SELECT cols."COLUMN_NAME"
  , COALESCE(translations."COLUMN_LANG_TITLE",cols."COLUMN_TITLE") AS "COLUMN_TITLE" 
  , options."OPTION_DESC"
FROM "EXTAPP_SETUP"."OBJECT_COLUMNS_TAB" cols 
LEFT OUTER JOIN "EXTAPP_SETUP"."COLUMN_LANG_TITLES_TAB" translations
  ON translations."EXTAPP_ID" = cols."EXTAPP_ID" 
    and translations."OBJECT_NAME" = cols."OBJECT_NAME" 
    and translations."COLUMN_NAME" = cols."COLUMN_NAME" 
    and translations."LANGUAGE_CODE" = 'fr' 
LEFT OUTER JOIN "EXTAPP_SETUP"."COL_FIX_OPTIONS_TAB" options
  ON options."EXTAPP_ID" = cols."EXTAPP_ID" 
    and options."OBJECT_NAME" = cols."OBJECT_NAME" 
    and options."COLUMN_NAME" = cols."COLUMN_NAME" 

【讨论】:

以上是关于PostgreSQL同表左外连接多表的主要内容,如果未能解决你的问题,请参考以下文章

sql多表连接查询问题

SQLServer 多表左连接

mysql4.0中一表关联多表左连接sql写法:

阶段3 1.Mybatis_09.Mybatis的多表操作_8 mybatis多对多操作-查询角色获取角色下所属用户信息

mysql优化5表左连接

MySql的回顾五:多表查询下(内联/左外/右外/自连接/交叉)-1999语法