0

我在 Oracle 10g 中有以下表:

Table1
Name  Status
a         closed
b         live
c         live

Table2
Name  Status
a         final
b         live
c         live

两个表中都没有主键,我正在尝试编写一个查询,该查询将返回相同的行,而无需循环两个表并比较行/列。如果状态列不同,则表 2 中的行优先。

所以在上面的例子中,我的查询应该返回这个:

Name   Status
a         final
b         live
c         live
4

2 回答 2

3

由于您提到两个表上都没有主键,所以我假设一行可能存在于Table1,Table2或两者上。下面的查询使用Common Table ExpressionandWindowing function来获得这样的结果。

WITH unionTable
AS
(
    SELECT  Name, Status, 1 AS ordr FROM Table1
    UNION 
    SELECT  Name, Status, 2 AS ordr FROM Table2
),
ranks 
AS
(
    SELECT  Name, Status,
            ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY ordr DESC) rn
    FROM    unionTable
)
SELECT  Name, Status
FROM    ranks
WHERE   rn = 1
于 2013-03-11T14:04:05.597 回答
1

像这样的东西?

SELECT table1.Name, table2.Status
FROM table1
INNER JOIN table2 ON table1.Name = table2.Name

By always returning table2.Status you've covered both the case when they're the same and when they're different (essentially it doesn't matter what the value of table1.Status is).

于 2013-03-11T14:04:13.967 回答