MySql - 如何使左连接表从表中按日期desc获得前1个订单?

时间:2013-12-29 18:52:45

标签: mysql

美好的一天。

例如,有2个表格 - Example1Example2

结构表Example1

idn(int 11)
username(int 11)
date(datetime)

行:

idn      username     date

10       test        01-12-2013 00:00

结构表Example2

idn(int 11)
val(int 11)
date(datetime)

行:

idn   val     date
10    100   01-12-2013 12:00
10    120   02-12-2013 12:00
10    110   02-12-2013 15:00
10    150   05-12-2013 12:00
10    90    08-12-2013 12:00

我希望得到username而他最后val(来自表格Example2)。

结果应该是:

username  val
test      90

为了得到它我使用:

SELECT 
  ex1.username, 
  ex2.val 
FROM Example1 ex1
left joing Example2 as ex2 on ex2.idn = ex1.idn

但是如何在查询中获取最后一个值val

请告诉我如何制作?

2 个答案:

答案 0 :(得分:0)

我希望我理解你的解释,请试试这个:

SELECT ex1.username,
       ex2.val
FROM Example1 AS ex1
LEFT JOIN Example2 AS ex2 ON ex1.idn = ex2.idn
WHERE ex1.username = 'test'
ORDER BY ex2.date DESC
LIMIT 1

答案 1 :(得分:0)

请试试sqlFiddle 我的示例中有2个用户名

SELECT 
  ex1.username, 
  (SELECT ex2.val FROM Example2 ex2
   WHERE ex2.idn = ex1.idn
   ORDER BY date DESC LIMIT 1) as val
FROM Example1 ex1
ORDER BY ex1.username