SQL:两个相似的查询合并为一个查询,这样 returns 一个 table 有两列
SQL: Two similar queries into one query such that returns one table with two columns
我想 运行 两个非常相似的查询,这样查询 return 一个 table 有两列(每个查询一列 运行)
查询 #1:
SELECT groupID
FROM tbl
WHERE username = 'admin' AND permission LIKE 'sample.%'
查询#2:
SELECT groupID
FROM tbl
WHERE username = 'administrator' AND permission LIKE 'sample.%'
想要return:
admin
administrator
groupID.1
groupID.1
groupID.3
groupID.2
可能吗?我能够通过执行 FULL OUTER JOIN 获得预期的 return,但我读到 JOINS 在两个 table 之间,而这只查看一个 table.
您可以尝试先为每个 table 的每一行分配一个行号,然后在这个排名中匹配两个 table:
WITH cte_admin AS (
SELECT groupID, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn
FROM tbl1
),
cte_administrator AS (
SELECT groupID, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn
FROM tbl2
)
SELECT t1.groupID AS g1,
t2.groupID AS g2
FROM cte_admin t1
INNER JOIN cte_administrator t2
ON t1.rn = t2.rn
UNION
SELECT t1.groupID AS g1,
t2.groupID AS g2
FROM cte_admin t1
LEFT JOIN cte_administrator t2
ON t1.rn = t2.rn
WHERE t2.rn IS NULL
UNION
SELECT t1.groupID AS g1,
t2.groupID AS g2
FROM cte_administrator t1
LEFT JOIN cte_admin t2
ON t1.rn = t2.rn
WHERE t2.rn IS NULL
如果您可以分享 table tbl
.
中的内容,我们将提供经过全面测试的解决方案
对于完全外部联接,需要三个联接:
INNER JOIN
来匹配两个 tables 之间对应的行号
LEFT JOIN from table1 to table2 WHERE table2 is null
以匹配来自 table1 的多余行,以防其行数多于 table2
LEFT JOIN from table2 to table1 WHERE table1 is null
以匹配来自 table2 的多余行,以防其行数多于 table1
伪测试完成here。
我想 运行 两个非常相似的查询,这样查询 return 一个 table 有两列(每个查询一列 运行)
查询 #1:
SELECT groupID
FROM tbl
WHERE username = 'admin' AND permission LIKE 'sample.%'
查询#2:
SELECT groupID
FROM tbl
WHERE username = 'administrator' AND permission LIKE 'sample.%'
想要return:
admin | administrator |
---|---|
groupID.1 | groupID.1 |
groupID.3 | groupID.2 |
可能吗?我能够通过执行 FULL OUTER JOIN 获得预期的 return,但我读到 JOINS 在两个 table 之间,而这只查看一个 table.
您可以尝试先为每个 table 的每一行分配一个行号,然后在这个排名中匹配两个 table:
WITH cte_admin AS (
SELECT groupID, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn
FROM tbl1
),
cte_administrator AS (
SELECT groupID, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn
FROM tbl2
)
SELECT t1.groupID AS g1,
t2.groupID AS g2
FROM cte_admin t1
INNER JOIN cte_administrator t2
ON t1.rn = t2.rn
UNION
SELECT t1.groupID AS g1,
t2.groupID AS g2
FROM cte_admin t1
LEFT JOIN cte_administrator t2
ON t1.rn = t2.rn
WHERE t2.rn IS NULL
UNION
SELECT t1.groupID AS g1,
t2.groupID AS g2
FROM cte_administrator t1
LEFT JOIN cte_admin t2
ON t1.rn = t2.rn
WHERE t2.rn IS NULL
如果您可以分享 table tbl
.
对于完全外部联接,需要三个联接:
INNER JOIN
来匹配两个 tables 之间对应的行号
LEFT JOIN from table1 to table2 WHERE table2 is null
以匹配来自 table1 的多余行,以防其行数多于 table2LEFT JOIN from table2 to table1 WHERE table1 is null
以匹配来自 table2 的多余行,以防其行数多于 table1
伪测试完成here。