我有兴趣比较两个表是否包含相同的数据。
我可以这样:
#standardSQL
SELECT
key1, key2
FROM
(
SELECT
table1.key1,
table1.key2,
table1.column1 - table2.column1 as col1,
table1.col2 - table2.col2 as col2
FROM
`table1` AS table1
LEFT JOIN
`table2` AS table2
ON
table1.key1 = table2.key1
AND
table1.key2 = table2.key2
)
WHERE
col1 != 0
OR
col2 != 0
但是当我想比较所有数字列时,这有点困难,尤其是当我想对多个表组合进行操作时。
因此,我的问题是:是否有人意识到可以对所有数字列进行迭代并将结果集限制为那些差异不为零的键?
答案 0 :(得分:5)
首先,我想提出有关您原始查询的问题
主要问题是1)使用LEFT JOIN; 2)使用col!= 0
下面是应如何对其进行修改以真正捕获两个表中的所有差异
运行原始查询,然后在其中一个查询下面运行-希望您会看到其中的区别
drop DATABASE rainbowonlineshopping;
或者您可以尝试对虚拟数据运行原始版本和更高版本,以查看差异
#standardSQL
SELECT key1, key2
FROM
(
SELECT
IFNULL(table1.key1, table2.key1) key1,
IFNULL(table1.key2, table2.key2) key2,
table1.column1 - table2.column1 AS col1,
table1.col2 - table2.col2 AS col2
FROM `table1` AS table1
FULL OUTER JOIN `table2` AS table2
ON table1.key1 = table2.key1
AND table1.key2 = table2.key2
)
WHERE IFNULL(col1, 1) != 0
OR IFNULL(col2, 1) != 0
第二,下面将大大简化您的整体查询
#standardSQL
WITH `table1` AS (
SELECT 1 key1, 1 key2, 1 column1, 2 col2 UNION ALL
SELECT 2, 2, 3, 4 UNION ALL
SELECT 3, 3, 5, 6
), `table2` AS (
SELECT 1 key1, 1 key2, 1 column1, 29 col2 UNION ALL
SELECT 2, 2, 3, 4 UNION ALL
SELECT 4, 4, 7, 8
)
SELECT key1, key2
FROM
(
SELECT
IFNULL(table1.key1, table2.key1) key1,
IFNULL(table1.key2, table2.key2) key2,
table1.column1 - table2.column1 AS col1,
table1.col2 - table2.col2 AS col2
FROM `table1` AS table1
FULL OUTER JOIN `table2` AS table2
ON table1.key1 = table2.key1
AND table1.key2 = table2.key2
)
WHERE IFNULL(col1, 1) != 0
OR IFNULL(col2, 1) != 0
您可以使用与上面相同的虚拟数据示例进行测试
注意:在此解决方案中,您无需选择特定的列-只需比较所有列即可!但是如果您只需要比较特定的列-仍然需要像下面的示例
#standardSQL
SELECT
IFNULL(table1.key1, table2.key1) key1,
IFNULL(table1.key2, table2.key2) key2
FROM `table1` AS table1
FULL OUTER JOIN `table2` AS table2
ON table1.key1 = table2.key1
AND table1.key2 = table2.key2
WHERE TO_JSON_STRING(table1) != TO_JSON_STRING(table2)
答案 1 :(得分:1)
在标准SQL中,我们发现在我们的用例中使用了两个UNION ALL
作品中的EXCEPT DISTINCT
:
(
SELECT * FROM table1
EXCEPT DISTINCT
SELECT * from table2
)
UNION ALL
(
SELECT * FROM table2
EXCEPT DISTINCT
SELECT * from table1
)
这将在两个方向上产生差异:
table1
中的行不在table2
中table2
中的行不在table1
中注意事项:
table1
和table2
的宽度必须相同,并且列的顺序和类型必须相同。STRUCT
或ARRAY
数据类型。您应该UNNEST
,或先使用TO_JSON_STRING
转换这些数据类型。GEOGRAPHY
一起使用,您必须先使用ST_AsText
转换为文本答案 2 :(得分:0)
您将需要指定哪些是数字列,但是查看所有数字列将进行快速比较:
#standardSQL
WITH table_a AS (
SELECT 1 id, 2 n1, 3 n2
), table_b AS (
SELECT 1 id, 2 n1, 4 n2
)
SELECT id
FROM table_a a
JOIN table_b b
USING(id)
WHERE TO_JSON_STRING([a.n1, a.n2]) != TO_JSON_STRING([b.n1, b.n2])