内部连接的更简单替代方案

Simpler alternative to inner join

是否可以在 table 中比较 2 table 秒的数据?

table 1

ID Val
1 Ann
2 Ben

table 2

ID Val
1 Ann
3 Cyc

输出

ID Val1 Val2 Match
1 Ann Ann 1
2 Ben 0
3 Cyc 0

UNION 将查询堆叠在顶部,因此最终会得到 4 行 (1,2,1,3)。并且 INNER JOIN 可能不是最好的解决方案,因为我们不知道哪个 table 更长?

(SELECT t1.id, t1.val, new.sum_val, t1.val = new.sum_val as Match
FROM t1

INNER JOIN 
(SELECT t2.id, SUM(t2.val) as sum_val
FROM t2
WHERE t2.date = TODAY()
GROUP BY t2.ID) new on t1.ID = t2.ID

WHERE t1.date = TODAY())

您可以使用完全联接。这大致是一个左连接和一个右连接。它保留来自 table 的所有行。如果存在匹配的合作伙伴行,则合并合作伙伴行,否则合作伙伴行的值保持 NULL.

SELECT coalesce(t1.id, t2.id) AS id,
       t1.val AS val1,
       t2.val AS val2,
       CASE
         WHEN t1.val = t2.val
               OR t1.val IS NULL
                  AND t2.val IS NULL THEN
           1
         ELSE
           0
       END AS match
       FROM "table 1" AS t1
            FULL JOIN "table 2" as t2
                      ON t2.id = t1.id;