子查询有两个表

时间:2017-12-18 14:25:46

标签: mysql sql select subquery recurrence

我有两张桌子:

__表R _____

ID.....CustID....DATE
1......1.........2000-01-01
2......2.........2000-01-02
3......2.........2000-01-03
4......2.........2000-02-22
5......1.........2000-03-23

__表客户______

ID....NAME
1.....Lucas
2.....Michael

请问,我怎么能做一个SELECT,它会从每个客户的NAME返回最后日期? (这样):

Lucas......2000-03-23
Michael....2000-02-22

3 个答案:

答案 0 :(得分:0)

您可以使用:

select c.name,  max(r.date) 
from table_customers c
join table_r r on r.custid = c.id
group by c.id,  c.name;

答案 1 :(得分:0)

您需要的选择,使用MAX将返回最新日期:

SELECT customer.name, MAX(r.date)

两张表中的join

FROM r INNER JOIN customer ON r.custid = customer.id

但是,如果您需要每个客户的最新日期,则需要group

GROUP BY r.custid;

答案 2 :(得分:0)

select c.name, r.date 
from table_customers c 
join table_r r on r.custid = c.id 
ORDER BY r.date DESC 
LIMIT 2 ;