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

前端 未结 4 1291
时光说笑
时光说笑 2021-01-17 22:42

I have 2 tables:

Table1:

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

Table2:

         


        
相关标签:
4条回答
  • 2021-01-17 23:26

    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
    
    0 讨论(0)
  • 2021-01-17 23:26

    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
    
    0 讨论(0)
  • 2021-01-17 23:29

    The best way to do it is to have CreatedAt and ModifiedAt fields in every table in database. Then you just add ORDER BY CreatedAd LIMIT 1. Not sure if your Time is what I mean.

    What you also have is ID. Now, if ID is AutoIncremental then job should be easy. Use ORDER BY id DESC LIMIT 1

    0 讨论(0)
  • 2021-01-17 23:30

    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
    
    0 讨论(0)
提交回复
热议问题