简体   繁体   中英

how to select one record from multi records of another table?

I have multiple tables, Table 1:

ID    Name
1     Adam
2     Bob

...

Table 2:

ID    Visit
1     2019-01-01
2     2019-01-02
1     2019-01-03
1     2019-01-04
2     2019-01-04
1     2019-01-05

...

I would like to get the most recent visit from table 2 for each name in Table 1, such as

Name    LastVisit
Adam    2019-01-05
Bob     2019-01-04

I tried join them together using

select tbl1.name as "Name", MAX(tbl2.visit) as LastVisit
from table1 tbl1 join table2 tbl2 on tbl1.id=tbl2.id;

but it is not working, how should I do this?

You just need a group by :

select t1.name, MAX(t2.visit) as LastVisit
from table1 t1 join
     table2 t2
     on t1.id = t2.id
group by t1.name;

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