-2

次の 2 つの table2 があります。

   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

ここで、col4=2 の Table2 からすべての値を見つけたいと思います。これにより、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 句の 2 つの条件で 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

結果を 1 列の 2 行として表示する場合:

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'

結果を 2 列の 1 行として表示する場合:

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 に答える