sql查询有效地连接2个表

时间:2013-10-22 05:37:32

标签: sql postgresql

有以下2表2:

   Table1(col1 integer, col2)
   1     "This is a string"
   2     "This is another string"
   5     "This is yet another string"
   3      "a"
   4      "b"
   6      "Some other string"

   Table2(col3 integer, col4 integer, col5 integer)
   1    2   5
   3    4   6

现在我想找到Table2中col4 = 2的所有值。这给了我col3 = 1和col5 = 5。现在我想将此结果与Table1连接,以便获取与这些整数对应的字符串值(col2)。

也就是说,我希望结果为:“这是一个字符串”,“这是另一个字符串”

我在postgresql中编写的SQL查询如下:

select d1.col2, d2.col2
from Table1 d1, Table1 d2
where (select col3, col5 from Table2 where col4=0);

但是,上面的查询给了我错误。有人可以帮我写一个有效的查询。

4 个答案:

答案 0 :(得分:2)

您可以在ON子句中使用带有两个条件的INNER JOIN:

SELECT Table1.*
FROM
  Table1 INNER JOIN Table2
  ON Table1.col1 = Table2.col3 OR Table1.col1 = Table2.col5
WHERE
  Table2.col4=2

请参阅小提琴here

答案 1 :(得分:0)

尝试将其作为联盟

select col2 from table1 where col1 in (
select col3 from table2 where col4 = 2
union
select col5 from table2 where col4 = 2
)

答案 2 :(得分:0)

尝试

SELECT t2.col2, t3.col2
FROM Table1 AS t1
INNER JOIN Table2 AS t2 ON t1.col1 = t2.col3
INNER JOIN Table2 AS t3 ON t1.col1 = t2.col5
WHERE t1.col4 = 2

答案 3 :(得分:0)

如果您希望结果为两行,只有一列:

select t1.col2
from Table2 as t2
    inner join Table1 as t1 on t1.col1 in (t2.col3, t2.col5)
where t2.col4 = 2;

-- output
-- 'This is a string'
-- 'This is yet another string'

如果您希望将结果作为一行包含两列:

select t13.col2, t15.col2
from Table2 as t2
    inner join Table1 as t13 on t13.col1 = t2.col3
    inner join Table1 as t15 on t15.col1 = t2.col5
where t2.col4 = 2

-- output
-- 'This is a string', 'This is yet another string'

<强> sql fiddle demo