如何使连接仅基于具有相同条件的列的最小值返回一行?

时间:2015-08-12 17:46:24

标签: mysql sql h2

我想说我需要这样做:

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')

如何撰写此查询?

3 个答案:

答案 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')