简体   繁体   English

MYSQL:仅选择最新记录(在左侧联接表上)

[英]MYSQL: select latest record only (on left join table)

I have 2 tables: 我有2张桌子:

Table1: 表格1:

ID | Mobile Number | Name | Ordered Product| Order Date

Table2: 表2:

ID(foreign_key can be inserted multipletimes in this table) |Contacted_for | Time(timestamp)

I need a query to display all the data in Table1 and if the ID is present in Table 2, I need to display the last inserted record on Table2(with time) of that ID 我需要一个查询来显示表1中的所有数据,如果表2中存在该ID,我需要在该ID的表2(随时间)上显示最后插入的记录

My query is 我的查询是

select a.* , b.* FROM table1 a LEFT JOIN table2 b ON a.ID=b.ID GROUP BY a.ID ORDER BY b.Time DESC

Here in my query when I remove Group By a.ID, it works but shows all results. 在此查询中,当我删除Group By a.ID时,它可以工作,但会显示所有结果。 But I want to show final record of table2 only(no duplicate ID records) 但我只想显示table2的最终记录(没有重复的ID记录)

Thanks in advance 提前致谢

You'll need some subquery's for that: 您将需要一些子查询:

SELECT
    a.*, b.*
FROM
    table1 a
LEFT JOIN
    (SELECT c.id, d.contacted_for, c.time
     FROM
         (SELECT
            id,
            MAX(time) time
         FROM
             table2
         GROUP BY id
         ) c
     JOIN
         table2 d
         ON c.id = d.id AND d.time = c.time
     ) b
     ON a.id = b.id

You can also try this way. 您也可以尝试这种方式。

Select * from table1 a left join
(Select * from table2 where id in (select max(id) from table2 group by id) ) b on a.id=b.id

The best way to do it is to have CreatedAt and ModifiedAt fields in every table in database. 最好的方法是在数据库的每个表中都有CreatedAtModifiedAt字段。 Then you just add ORDER BY CreatedAd LIMIT 1 . 然后,您只需添加ORDER BY CreatedAd LIMIT 1 Not sure if your Time is what I mean. 不知道您的Time是否就是我的意思。

What you also have is ID. 您还拥有ID。 Now, if ID is AutoIncremental then job should be easy. 现在,如果IDAutoIncremental则工作应该很容易。 Use ORDER BY id DESC LIMIT 1 使用ORDER BY id DESC LIMIT 1

Try this ... I hope it may works 试试这个...我希望它可能会起作用

select a.* , b1.* 
FROM table1 a 
LEFT JOIN table2 b1
ON ( a.ID=b1.ID)  
LEFT JOIN table2 b2
ON ( a.ID=b1.ID)  AND 
(b1.Time < b2.Time OR b1.Time = b2.Time AND b1.ID < b2.ID)
WHERE b2.ID IS NULL
GROUP BY a.ID ORDER BY b1.Time DESC

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

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