0

是否可以在一张表中比较 2 张表中的数据?

表格1

ID 瓦尔
1
2

表 2

ID 瓦尔
1
3 循环

输出

ID val1 VAL2 匹配
1 1
2 0
3 循环 0

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

(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())
4

1 回答 1

1

您可以使用完全联接。这大致是一个左和右连接。它保留两个表中的所有行。如果存在匹配的合作伙伴行,则组合合作伙伴行,如果没有,则保留合作伙伴行的值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;
于 2022-01-14T16:21:38.633 回答