在Mysql中优化Union查询

时间:2018-12-04 07:08:01

标签: mysql query-optimization union

我有这个查询

SELECT 
    ID, isDebit, AccountID, SUM(Amount) AS Amount
FROM
    journaltransactions
WHERE
    AccountID <> 78 and date between '2018-11-29' and '2018-11-29'
    union
    SELECT 
    ID, isDebit, AccountID, SUM(Amount) AS Amount
FROM
    journaltransactions
WHERE
    AccountID <> 795 and date between '2018-11-29' and '2018-11-29'
    union
    SELECT 
    ID, isDebit, AccountID, SUM(Amount) AS Amount
FROM
    journaltransactions
WHERE
    AccountID <> 56 and date between '2018-11-29' and '2018-11-29'
    union
    SELECT 
    ID, isDebit, AccountID, SUM(Amount) AS Amount
FROM
    journaltransactions
WHERE
    AccountID <> 89 and date between '2018-11-29' and '2018-11-29'
    union
    SELECT 
    ID, isDebit, AccountID, SUM(Amount) AS Amount
FROM
    journaltransactions
WHERE
    AccountID <> 90 and date between '2018-11-29' and '2018-11-29'

这里78,795,56,89,90是该条件的一组帐户ID,如果ID数量增加到我需要添加的联合数量

任何人都可以帮助我优化此查询,以达到更好的效果

2 个答案:

答案 0 :(得分:1)

您可以使用NOT IN

SELECT 
    ID, isDebit, AccountID, SUM(Amount) AS Amount
FROM
    journaltransactions
WHERE
    AccountID NOT IN (78,795,56,89,90) and date between '2018-11-29' and '2018-11-29'

注意:由于您在SQL中使用了SUM,因此需要使用GROUP BY来获得所需的结果


对于您的问题,请尝试以下操作,在这种情况下,我们从另一个相同的表中获取ID,然后使用<>获取结果

SELECT 
    a.ID, a.isDebit, a.AccountID, SUM(a.Amount) AS Amount
FROM
    journaltransactions a
    JOIN journaltransactions b ON b.id IN (78,795,56,89,90);
WHERE
    BETWEEN '2018-11-29' AND '2018-11-29'
    AND a.id<>b.id
GROUP BY a.id

答案 1 :(得分:0)

请考虑以下内容。我省略了SUM,因为尚不清楚应该累加什么。

SELECT 
    ID, isDebit, AccountID
FROM
    journaltransactions
WHERE
   AccountID NOT IN (78,795,56,89,90) 
   and date = '2018-11-29'