连接两个查询以获得笛卡尔积

lh80um4z  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(334)

我有个问题

SELECT 
d.GUID, w.word
FROM
dictionary d
    JOIN
word w ON w.ID = d.ID_word
WHERE
w.id_language = #ID#;

如果 #ID# = 1 它返回表

GUID | word
-----------
1    | A
2    | B
3    | C1
3    | C2
4    | D1
4    | D2
5    | E

如果 #ID# = 2 它返回表

GUID | word
-----------
1    | AA
2    | BB1
2    | BB2
3    | CC
4    | DD1
4    | DD2
6    | FF

现在我想合并这两个表/查询,得到一个如下所示的表:

GUID | word1 | word2
--------------------
1    | A     | AA
2    | B     | BB1
2    | B     | BB2
3    | C1    | CC
3    | C1    | CC
4    | D1    | DD1
4    | D1    | DD2
4    | D2    | DD1
4    | D2    | DD2

所以基本上它是一个表,由具有相同guid的行的笛卡尔积组成

sr4lhrrt

sr4lhrrt1#

您不需要子查询:

SELECT d1.GUID, w1.word, w2.word
FROM dictionary d1 JOIN
     word w1
     ON w1.ID = d1.ID_word JOIN
     dictionary d2
     ON d2.GUID = d.GUID JOIN
     word w2
     ON w2.id = d2.ID_word
WHERE w1.id_language = ? AND
      w2.id_language = ?;

我认为使用CTE更容易阅读:

WITH dw AS (
      SELECT d.GUID, w.word, w.id_language
      FROM dictionary d JOIN
         word w
         ON w.ID = d.ID_word
     )
SELECT dw1.GUID, dw1.word, dw2.word
FROM dw dw1 JOIN
     dw dw2
     ON dw1.GUID = dw2.GUID
WHERE dw1.id_language = ? AND
      dw2.id_language = ?;

在这两个例子中(以及你的问题所暗示的),只有一个单词的guid被过滤掉。这些可以通过调整查询来包含。

olhwl3o2

olhwl3o22#

select *
from 
 (  -- if #ID# = 1 it returns table
    SELECT 
    d.GUID, w.word
    FROM
    dictionary d
        JOIN
    word w ON w.ID = d.ID_word
    WHERE
    w.id_language = 1
 ) as t1
join
 (  -- if #ID# = 2 it returns table
    SELECT 
    d.GUID, w.word
    FROM
    dictionary d
        JOIN
    word w ON w.ID = d.ID_word
    WHERE
    w.id_language = 2
 ) as t2
-- Cartesian product of the rows with the same GUID
on t1.guid = t2.guid
t9eec4r0

t9eec4r03#

你可以 JOIN 你的两个问题 GUID :

SELECT q1.GUID, q1.word AS word1, q2.word AS word2
FROM (
    SELECT 
    d.GUID, w.word
    FROM
    dictionary d
        JOIN
    word w ON w.ID = d.ID_word
    WHERE
    w.id_language = 1
) q1
JOIN (
    SELECT 
    d.GUID, w.word
    FROM
    dictionary d
        JOIN
    word w ON w.ID = d.ID_word
    WHERE
    w.id_language = 1
) q2 ON q2.GUID = q1.GUID

相关问题