Mysql union优先级

时间:2015-03-01 10:36:51

标签: mysql sql

我有3个表,我的查询是:

SELECT BRAND, AMOUNT FROM
(
SELECT BRAND, AMOUNT FROM SALES1 
UNION
SELECT BRAND, AMOUNT FROM SALES2
UNION
SELECT BRAND, AMOUNT FROM SALES3
)

SALES 1表有品牌: A 和AMOUNT: 50

SALES 3表有品牌: A AND AMOUNT: 100

我想获得金额50而忽略100.我想问一下使用工会时是否有优先权?

3 个答案:

答案 0 :(得分:0)

您需要"where not exists"内的"not in"(或"left join"union}:

(SELECT BRAND, AMOUNT FROM SALES1 )
UNION 
(SELECT BRAND, AMOUNT FROM SALES2) 
UNION 
(SELECT BRAND, AMOUNT FROM SALES3 where brand not in (SELECT BRAND FROM SALES1))

答案 1 :(得分:0)

如果您想要第一次出现,则应使用union all而不是union。这对于性能原因很重要,因为union会进行不必要的重复消除。

然后对每个子查询使用not exists子句:

(SELECT BRAND, AMOUNT
 FROM SALES1 
) UNION ALL
(SELECT BRAND, AMOUNT
 FROM SALES2 s2
 WHERE NOT EXISTS (SELECT 1 FROM SALES1 s1 WHERE s1.BRAND = s2.BRAND)
) UNION ALL
(SELECT BRAND, AMOUNT
 FROM SALES3 s3
 WHERE NOT EXISTS (SELECT 1 FROM SALES1 s1 WHERE s1.BRAND = s3.BRAND) AND
       NOT EXISTS (SELECT 1 FROM SALES2 s2 WHERE s2.BRAND = s3.BRAND)
)

答案 2 :(得分:0)

SELECT  BRAND, AMOUNT
    FROM  
      ( SELECT  BRAND, AMOUNT, 1 AS priority
            FROM  SALES1
            UNION  ALL 
        SELECT  BRAND, AMOUNT, 2 AS priority
            FROM  SALES2
            UNION  ALL 
        SELECT  BRAND, AMOUNT, 3 AS priority
            FROM  SALES3 
      )
    ORDER BY  priority
    LIMIT  1;