-2

有以下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

现在我想从表 2 中找到 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

4 回答 4

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

在此处查看小提琴。

于 2013-10-22T05:49:25.710 回答
0

尝试作为一个工会

select col2 from table1 where col1 in (
select col3 from table2 where col4 = 2
union
select col5 from table2 where col4 = 2
)
于 2013-10-22T05:43:44.213 回答
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
于 2013-10-22T05:50:57.803 回答
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

于 2013-10-22T06:26:49.667 回答