表1
|id | name |
|1 | Test |
|2 | Hello|
|3 | Hii |
表2
|id | related_id | date | time
|1 | 1 | 2014-09-11 | 12.56.25
|2 | 2 | 2014-09-11 | 12.56.25
|3 | 2 | 2014-09-12 | 11.56.25
|4 | 2 | 2014-09-12 | 12.56.31 (Last record)
输出
|id | name | date | time
|1 | test | 2014-09-11 | 12.56.25
|2 | Hello | 2014-09-12 | 12.56.31 (This is the last record from table 2)
|3 | Hii | - | -
输出表中的SO,Id = 2是表2的最后一条记录,其中相对id = 2 ...我也想要表1中的所有记录。
那么我可以使用哪种加入查询?
答案 0 :(得分:1)
您可以使用table2的自联接来获取每个related_id
组的最后一行,并使用带内部选择的左连接和table1
select a.*,
d.`date`,
d.`time`
from table1 a
left join (
select b.*
from table2 b
inner join (
select
max(id) id ,
related_id
from table2
group by related_id ) c
on(b.id=c.id and b.related_id = c.related_id)
) d
on(a.id = d.related_id)
另一种方法是使用substring_index
和group_concat
按顺序使用
select a.*,
substring_index(group_concat(b.`date` order by b.id desc),',',1) `date`,
substring_index(group_concat(b.`time` order by b.id desc),',',1) `time`
from table1 a
left join table2 b
on(a.id = b.related_id)
group by a.id