美好的一天。
例如,有2个表格 - Example1
和Example2
结构表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
?
请告诉我如何制作?
答案 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