Mysql表关联时执行顺序
with temp1 as (
select 1 as id ,12 as num union
select 2 as id ,13 as num union
select 3 as id ,12 as num union
select 4 as id ,14 as num union
select 5 as id ,12 as num union
select 6 as id ,16 as num
), temp2 as (
select 1 as id ,'a' as var union
select 2 as id ,'b' as var union
select 3 as id ,'c' as var union
select 4 as id ,'a' as var union
select 5 as id ,'b' as var union
select 6 as id ,'f' as var
)
select * from temp1 t1 left join temp2 t2 on t1.id =t2.id
说明:先关联,再过滤
with temp1 as (
select 1 as id ,12 as num union
select 2 as id ,13 as num union
select 3 as id ,12 as num union
select 4 as id ,14 as num union
select 5 as id ,12 as num union
select 6 as id ,16 as num
), temp2 as (
select 1 as id ,'a' as var union
select 2 as id ,'b' as var union
select 3 as id ,'c' as var union
select 4 as id ,'a' as var union
select 5 as id ,'b' as var union
select 6 as id ,'f' as var
)
-- select * from temp1 t1 left join temp2 t2 on t1.id =t2.id
select * from temp1 t1 left join temp2 t2 on t1.id =t2.id and t1.num=12
-- select * from temp1 t1 left join temp2 t2 on t1.id =t2.id where t1.num=12
说明:最后过滤
with temp1 as (
select 1 as id ,12 as num union
select 2 as id ,13 as num union
select 3 as id ,12 as num union
select 4 as id ,14 as num union
select 5 as id ,12 as num union
select 6 as id ,16 as num
), temp2 as (
select 1 as id ,'a' as var union
select 2 as id ,'b' as var union
select 3 as id ,'c' as var union
select 4 as id ,'a' as var union
select 5 as id ,'b' as var union
select 6 as id ,'f' as var
)
-- select * from temp1 t1 left join temp2 t2 on t1.id =t2.id
-- select * from temp1 t1 left join temp2 t2 on t1.id =t2.id and t1.num=12
select * from temp1 t1 left join temp2 t2 on t1.id =t2.id where t1.num=12
with temp1 as (
select 1 as id ,12 as num union
select 2 as id ,13 as num union
select 3 as id ,12 as num union
select 4 as id ,14 as num union
select 5 as id ,12 as num union
select 6 as id ,16 as num
), temp2 as (
select 1 as id ,'a' as var union
select 2 as id ,'b' as var union
select 3 as id ,'c' as var union
select 4 as id ,'a' as var union
select 5 as id ,'b' as var union
select 6 as id ,'f' as var
)
select * from temp1 t1 left join temp2 t2 on t1.id =t2.id and t1.num=12 where t1.num=12