set @type = (SELECT CASE WHEN (подзапрос) = 0
THEN 'left'
ELSE 'inner'
END)@type JOIN table ON ... select a.*, b.*
from table1 a
left join table2 b on (a.id = b.id)
where 1=1 /*постоянное*/
and b.id is not null /*при наличии этой строки будет inner join для left join*/
with table1 as(
select 1 id, 'table1_1' text1 union all
select 2,'table1_2' union all
select 3,'table1_3' union all
select 4,'table1_4' union all
select 5,'table1_5'
)
,table2 as (
select 1 id2, 1 tab1_id,'table2_1' text2 union all
select 2, 1 tab1_id,'table2_2' union all
select 3, 1 tab1_id,'table2_3' union all
select 4, 2 tab1_id,'table2_4' union all
select 5, 2 tab1_id,'table2_5' union all
select 6, 2 tab1_id,'table2_6' union all
select 7, 3 tab1_id,'table2_7' union all
select 8, 3 tab1_id,'table2_8' union all
select 9, 3 tab1_id,'table2_9' )
SELECT *
from table1 a
left join table2 b on (a.id = b.tab1_id)SELECT *
from table1 a
left join table2 b on (a.id = b.tab1_id)
where b.tab1_id is not nullSELECT *
from table1 a
inner join table2 b on (a.id = b.tab1_id)
select *
from (SELECT @row_num := CASE WHEN @row_num_val = a.id THEN @row_num+1
WHEN (@row_num_val := a.id) IS NOT NULL THEN 1
END pair_flag, a.*, b.*
from (SELECT @row_num := null, @row_num_val := null) AS x,
table1 a
left join table2 b on (a.id = b.tab1_id)) t1
where pair_flag <= 2