基于右表

时间:2016-06-09 20:14:54

标签: mysql join sql-order-by limit

我正在尝试在MySQL中连接两个表,并且只显示一行,它应该是基于日期字段的右表中的最新行。

用户

id    name
1     John
2     James
3     Peter

订单

id    user_id   value   order_date
1     1         35      2016-06-01
2     1         25      2016-06-05
3     1         10      2016-06-07
4     2         20      2016-06-02
5     3         18      2016-06-07

预期输出

John 10 2016-06-07
James 20 2016-06-02
Peter 18 2016-06-07

查询

select 
    name, value, order_date 
from 
    users 
left join 
    orders on users.id = orders.user_id

收到输出

John 35 2016-06-01
John 25 2016-06-05
John 10 2016-06-07
James 20 2016-06-02
Peter 18 2016-06-07

我无法在整体查询中添加限制1或顺序,因为这只会返回一行不正确的一行,所以有些需要如何添加到连接中但是我无法弄清楚如何?我假设某种子查询,但是我在select或join中做了子查询,还是两者都有?

3 个答案:

答案 0 :(得分:0)

如果您确定每个日期每个user_id只有1条记录

你可以这样使用MAX()

http://sqlfiddle.com/#!9/658ce/5

SELECT 
    name, 
    o.value, 
    o.order_date 
FROM users 
LEFT JOIN
  (SELECT 
      user_id,
      MAX(order_date) max_date
   FROM orders 
   GROUP BY user_id
  ) orders
ON users.id = orders.user_id
LEFT JOIN
    orders o 
ON o.user_id = orders.user_id
  AND orders.max_date = o.order_date

答案 1 :(得分:0)

您可以尝试这样的事情:

select name, value, order_date 
from users 
left join orders o on users.id = o.user_id
where not exists (
    select 1
    from orders o2
    where o2.user_id = o.user_id
      and o2.id > o.id
)

答案 2 :(得分:0)

您可以使用in(子查询为max(order_date,user_id))

SELECT 
u.name
, o.value
, o.order_date 
from user as u 
inner join orders o on u.user_id = o.user_id
and (o.user_id, o.order_date in (user_id, max(order_date) 
                                   from orders group by user_id)