如何在给定查询中使用内连接并进行优化?

时间:2017-03-19 13:48:24

标签: sql optimization

我有下面的查询,我想优化它们。

car_wheels AS (
    SELECT wheel FROM devices WHERE type = '4x4'
),
white_wheels AS (
    SELECT wheel FROM devices WHERE color = 'white'
),
car_white_wheels AS (
    SELECT * FROM car_wheels INTERSECT SELECT * FROM white_wheels
)

SELECT wheel FROM devices JOIN users ON devices.user_id = user.id WHERE wheel IN (SELECT wheel FROM car_white_wheels) AND users.organization_id = 999;

我有一个想法在这里使用内部联接。它是否正确?我还可以在这里轻松优化什么?

我想为给定的user.organization_id找到白色car_wheels。

1 个答案:

答案 0 :(得分:1)

这样做怎么样?

select wheel
from devices d join
     users u
     on d.user_id = u.id
where (type = '4x4' and color = 'white') and
      u.organization_id = 999;

我错过了什么吗?

或者,如果wheel可以在多行上有功能:

select wheel
from devices d join
     users u
     on d.user_id = u.id
where (type = '4x4' or color = 'white') and
      u.organization_id = 999
group by wheel
having sum(case when type = '4x4' then 1 else 0 end) > 0 and
       sum(case when color = 'white' then 1 else 0 end) > 0';