简体   繁体   English

如何在mysql中使用JOIN Query提取不同的值以及最后一条记录?

[英]How can I fetch Distinct Value as well as last record using JOIN Query in mysql?

table 1 表格1

|id | name |

|1 | Test |

|2 | Hello|

|3 | Hii |

table 2 表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)

OUTPUT OUTPUT

|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 in output table, Id=2 is last record of table 2 where relative id=2 ... and I also want all records from table 1. 因此在输出表中,Id = 2是表2的最后一条记录,其中相对id = 2 ...,我也希望表1中的所有记录。

So Which kind of Join Query I can use? 那么我可以使用哪种联接查询?

You can do so by using self join for table2 to get the last row for each related_id group and use left join with inner select with your table1 您可以通过对表2使用自联接来获取每个related_id组的最后一行,并在表1中使用带有内部选择的左联接来做到这一点。

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)

Demo

Another way would be use substring_index and group_concat with order by 另一种方法是按顺序使用substring_indexgroup_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

Demo 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM