How to select last date in 2 records in Mysql ?
TABLE A
SID NAME Sex
1 Jam M
2 Da F
TABLE B
ID Title SID Date
1 A 1 2012-07-31 09:57:10
2 NULL 1 2012-07-31 09:57:13
3 A 2 2012-07-31 10:10:13
4 NULL 2 2012-07-31 10:57:13
I want to inner join those two tables,
but select only one record only of Table B(distinct of SID) where title not null then show the
biggest Date of title is null field.
Result want the biggest Date of Null title:
ID Name Title SID Date
1 Jam A 1 **2012-07-31 09:57:13**
2 DA A 2 **2012-07-31 10:57:13**
How to do that ?
I think something like this will work for you:
SELECT b.ID, a.NAME, b.Title, b.SID, b.Date
FROM TABLEA a
INNER JOIN (SELECT SID, IFNULL(Title, "") AS Title,
MAX(IF(Title IS NULL, Date, NULL)) Date
FROM TABLEB GROUP BY SID) b
ON a.SID = b,SID;
SELECT b.ID, a.NAME, b.Title, b.SID, b.Datea
from tablea a left outer join
(( SELECT sid, MAX(datea) AS latest
FROM tableb
where title is not null
GROUP BY sid) AS dt
INNER JOIN tableb b ON b.sid= dt.sid and b.datea=dt.latest )
on a.sid=b.sid
Try my code (it works):
SELECT b.id, b.title, b.sid, b.date
FROM table_b as b
JOIN table_a as a ON a.sid = b.sid
WHERE b.id in (SELECT MAX(id) FROM table_b GROUP BY sid)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.