我想说我需要这样做:
select
*
from
table1
left join table2 as tba on tba.column1 = table1.column1 and tba.column2 = 'A'
left join table2 as tbb on tbb.column1 = table1.column1 and tbb.column2 = 'B'
left join table2 as tbc on tbc.column1 = table1.column1 and tbc.column2 = 'C'
唯一的一点是,对于table2上的每个连接,它可以返回多行,我只需要根据column3的最小值返回一行。
所以我需要做的是这样的事情:
select
*
from
table1
left join table2 as tba on tba.column1 = table1.column1 and tba.column2 = 'A' and tb2.colum3 has the less value from all the other with same conditions (tba.column1 = table1.column1 and tba.column2 = 'A')
left join table2 as tbb on tbb.column1 = table1.column1 and tbb.column2 = 'B' and tb2.colum3 has the less value from all the other with same conditions (tba.column1 = table1.column1 and tba.column2 = 'B')
left join table2 as tbc on tbc.column1 = table1.column1 and tbc.column2 = 'C' and tb2.colum3 has the less value from all the other with same conditions (tba.column1 = table1.column1 and tba.column2 = 'C')
如何撰写此查询?
答案 0 :(得分:0)
您需要有一个子查询,例如:
select * from table1 left join
(select column1, min(column3) from table2 where column2 = 'A' group by column1) tba on tba.column1 = table1.column1
您可以通过添加where column2 in ('A', 'B', 'C')
答案 1 :(得分:0)
您需要使用CASE声明,否则您将无法获得所需内容。
答案 2 :(得分:0)
我最后做了一个子查询。
left join table2 as tba on tba.column1 = table1.column1 and tba.column2 = 'A' and tba.colum3 = (select min(column3) from table2 wherecolumn1 = table1.column1 and column2 = 'A')