I have 2 tables:
Table1:
ID | Mobile Number | Name | Ordered Product| Order Date
Table2:
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
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
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
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