MySQL –左连接在右表中的最后一条记录上

时间:2019-11-27 05:17:58

标签: mysql

我需要一个使用LEFT JOIN的查询,在这里可以找到表2的最后一条记录。为此,我正在表2中表1的“ {{1}”中查找表“ Id” }}”。

必须为此扩展当前查询。我尝试了几种方法,但没有成功。我希望你能帮助我。

https://murrayhopkins.wordpress.com/2008/10/28/mysql-left-join-on-last-or-first-record-in-the-right-table/

表1

channel

表2

id  id1  id2 g_id1  g_id2   datum
1    1    2    x     x    timestamp
2    3    1    x     x    timestamp  
3    3    2    x     x    timestamp

表3

n_id    channel absender     nachricht            datum
1         1        2        messagetext1    2019-09-22 19:30:31
2         1        1        messagetext2    2019-09-22 19:35:31  
3         2        1        messagetext3    2019-09-22 19:40:31
3         2        3        messagetext4    2019-09-22 19:42:31
4         3        2        messagetext5    2019-09-22 20:40:31

输出

id    firmenname  
1    companyname1
2    companyname2    
3    companyname3    

我当前的查询

id  id1  id2 g_id1  g_id2   datum      firmenname     firmenname2   nachricht
1    1    2    x     x    timestamp   companyname1   companyname2  messagetext2
2    2    1    x     x    timestamp   companyname2   companyname1  messagetext4
3    3    2    x     x    timestamp   companyname3   companyname2  messagetext5

声明 表1 id是ChannelId。我需要表1的孔和表2中此通道的最后一条消息。在表3中具有LIMIT和公司名称(firmenname)。在当前查询中,仅缺少表2中最后一条消息的部分。 1和2来自表3我需要

SELECT a.*, b.firmenname as firmenname1, c.firmenname as firmenname2 FROM nachrichtensystem a LEFT JOIN spieler b ON a.id1 = b.id LEFT JOIN spieler c ON a.id2 = c.id WHERE id1 = $sp_id OR id2 = $sp_id ORDER BY a.timestamp DESC LIMIT $id, 8

1 个答案:

答案 0 :(得分:1)

您需要一个子查询,该查询返回每个通道的最后一条消息并联接到table1,然后联接table3两次:

select t1.*, t31.firmenname, t32.firmenname firmenname2, t2.nachricht 
from table1 t1 
left join (
  select t.* from table2 t
  where not exists (
    select 1 from table2
    where channel = t.channel and datum > t.datum
  )
) t2 on t2.channel = t1.id
left join table3 t31 on t31.id = t1.id1
left join table3 t32 on t32.id = t1.id2
order by t1.id

请参见demo
结果:

| id  | id1 | id2 | g_id1 | g_id2 | datum     | firmenname   | firmenname2  | nachricht    |
| --- | --- | --- | ----- | ----- | --------- | ------------ | ------------ | ------------ |
| 1   | 1   | 2   | x     | x     | timestamp | companyname1 | companyname2 | messagetext2 |
| 2   | 3   | 1   | x     | x     | timestamp | companyname3 | companyname1 | messagetext4 |
| 3   | 3   | 2   | x     | x     | timestamp | companyname3 | companyname2 | messagetext5 |