如何在不使用UNION的情况下优化sql中的查询

时间:2014-10-05 15:47:17

标签: mysql optimization

我的查询为:

SELECT i.id AS id
    FROM table_a i
    WHERE (i.cat_id IN (92, 224))
    GROUP BY id
    HAVING (COUNT(i.cat_id) = 2 AND SUM(i.cat_id) = 316)

    UNION
    (
        SELECT i.id AS id
        FROM table_a i
        WHERE (i.cat_id IN (92, 227))
        GROUP BY id
        HAVING (COUNT(i.cat_id) = 2 AND SUM(i.cat_id) = 319)
    )

如何优化此查询?

1 个答案:

答案 0 :(得分:1)

SELECT i.id AS id
    FROM table_a i
    WHERE (i.cat_id IN (92, 224) OR i.cat_id IN (92, 227))
    GROUP BY id
    HAVING (COUNT(i.cat_id) = 2 
       AND (SUM(i.cat_id) = 316 OR SUM(i.cat_id) = 319 )