MySQL UNION查询,不同的ID

时间:2012-12-06 23:36:41

标签: mysql distinct union

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

目前我有这个问题:

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

似乎有用。但是 -

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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