简体   繁体   中英

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

table 1

|id | name |

|1 | Test |

|2 | Hello|

|3 | Hii |

table 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

|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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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