簡體   English   中英

如何在mysql中使用JOIN Query提取不同的值以及最后一條記錄?

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

表格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)

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

因此在輸出表中,Id = 2是表2的最后一條記錄,其中相對id = 2 ...,我也希望表1中的所有記錄。

那么我可以使用哪種聯接查詢?

您可以通過對表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

另一種方法是按順序使用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