简体   繁体   中英

Join newest row off second table to each row of first table

I have two tables:

Table 1
ID    Username
1     human
2     humane
3     humaner

Table 2
ID    userID  date        data1  data2
1     1       2017-10-25  25     12
2     1       2017-10-24  11     13
3     2       2017-10-25  43     24

And I want to join only the newest data of table 2 like this:

username  date         data1  data2
human     2017-10-25   25     12
humane    2017-10-25   43     24

How can I realize this in mysql with php? I tried to do it with 2 connections but I think it's not really performant :)

 SELECT  t1.*, t2.*
 FROM Table1 t1
 JOIN Table2 t2
   ON t1.ID = t2.user_id
 WHERE NOT EXISTS (SELECT 1
                   FROM Table2 Q
                   WHERE Q.user_id = t2.user_id
                     AND Q.date > t2.date)

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.

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