1

我有两个包含(ID,值)的表。ID 可以在一个或两个表中找到。我需要一个包含所有唯一 ID 及其值的记录集;如果 ID 出现在两个表中,我需要表 2 中的值。

目前我有这个查询:

SELECT * FROM
(SELECT * FROM table2 UNION SELECT * FROM table1) as temp
GROUP BY id

这似乎有效。然而 -

  1. 如果 ID 在两个表中,这是否保证从 table2 返回值?

  2. 如果没有,我该怎么做?

  3. 无论如何,有没有更好的方法呢?

4

2 回答 2

0

试试这个,

SELECT  a.*
FROM    
        (
            SELECT *, 1 AS TB FROM table1  -- assuming you have many columns
            UNION ALL
            SELECT *, 2 AS TB FROM table2
        ) a INNER JOIN
        (
            SELECT ID, MAX(TB) maxTB
            FROM 
            (
                SELECT ID, 1 AS TB FROM table1
                UNION ALL
                SELECT ID, 2 AS TB FROM table2
            ) s
            GROUP BY ID
        ) b ON  a.ID = b.ID AND 
                a.tb = b.maxTB
于 2012-12-06T23:48:02.553 回答
0

投入我的两分钱

SELECT ISNULL(TB2.Id, TB1.Id) As Id,
       ChooseValue(TB2.Id, TB2.Value, TB1.Values) As Value
FROM TABLE2 AS TB2
FULL OUTER JOIN TABLE1 AS TB1
ON TB2.Id = TB1.Id

这避免了额外连接或额外运行表或 group by 子句的成本,这些成本可能很昂贵。

CREATE FUNCTION ChooseValue(DeciderValue IN VAR_TYPE, Table_2Value IN VARTYPE, Table_1Value  IN VARTYPE)
RETURNS VARTYPE
BEGIN
    DECLARE returnValue VARTYPE;
    IF DeciderValue IS NULL THEN
        returnValue = Table_2Value
    ELSE
        returnValue = Table_1Value
    END IF
RETURN returnValue
END
于 2012-12-07T07:15:16.817 回答