【问题标题】:Join table twice - on two different columns of the same table加入表两次 - 在同一个表的两个不同列上
【发布时间】:2012-05-29 10:19:50
【问题描述】:

我有一个非常混乱的数据库,其中一个表在单独的表中保存了我需要的两个值。这是我的问题:

Table1
- id

Table2
- id
- table1_id
- table3_id_1
- table3_id_2

Table3
- id
- value

我需要从 table1 开始并进行连接,这将使我在两个单独的列中返回来自 table3 的值。所以我想要这样的东西:

table1.id | table2.id | table2.table3_id_1 | table2.table3_id_2 | X | Y

其中XY 是分别由table3_id_1table3_id_2 连接的行的值。

可能使它们成为变量或其他东西,以便我也可以在WHERE 子句中过滤它们?

【问题讨论】:

    标签: sql postgresql join foreign-keys left-join


    【解决方案1】:
    SELECT t2.table1_id
         , t2.id          AS table2_id
         , t2.table3_id_1
         , t2.table3_id_2
         , t31.value      AS x
         , t32.value      AS y
    FROM   table2 t2
    LEFT   JOIN table3 t31 ON t31.id = t2.table3_id_1
    LEFT   JOIN table3 t32 ON t32.id = t2.table3_id_2;
    

    没有必要涉及table1table2 拥有你所需要的一切——假设有一个 foreign key constraint 保证引用完整性(所有 t2.table1_id 实际上都存在于 table1 中)。否则,您可能想要加入 table1,从而只选择同样存在于 table1 中的行。

    出于类似的原因,我使用LEFT [OUTER] JOIN (and not [INNER] JOIN) 加入table3 的两个实例:不清楚是否保证了引用完整性——以及是否有任何关键列可以是NULL[INNER] JOIN 将从结果中删除未找到匹配项的行。我假设您宁愿为任何缺少的 xy 显示带有 NULL 值的此类行。

    table3.id 必须是 UNIQUE,否则我们可能会将行与来自每个 LEFT JOIN 的多个匹配项相乘:

    【讨论】:

      【解决方案2】:

      如果你多次加入一个表,使用别名来区分它们:

      SELECT table1.id,table2.id,table2.table3_id_1,table2.table3_id_2,t3_1.id,t3_2.id
      FROM table1
      JOIN table2 ON table1.id=table2.table1_id
      JOIN table3 t3_1 ON table2.table3_id_1=t3_1.id
      JOIN table3 t3_2 ON table2.table3_id_2=t3_2.id
      WHERE ... t3_1.id=... AND ... t3_2.id=...
      

      【讨论】:

        【解决方案3】:
        select t1.id as table1_id, 
            t2.id as table2_id, 
            t2.table3_id_1, 
            t2.table3_id_2,
            t3_1.value as X, 
            t3_2.value as Y
        from Table1 t1
        inner join Table2 t2 on t1.id = t2.table1_id
        inner join Table3 t3_1 on t2.table3_id_1 = t3_1.id
        inner join Table3 t3_2 on t2.table3_id_2 = t3_2.id
        where t3_1.value = 'some_value'
            or t3_2.value = 'some_other_value'
        

        【讨论】:

          猜你喜欢
          • 2015-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-09
          • 1970-01-01
          • 2017-01-22
          • 1970-01-01
          相关资源
          最近更新 更多