我有两张表raw_materials
和raw_materials_moves
。
raw_materials
有字段
id, name
raw_materials_moves
有此字段
id, raw_material_id, price, created
所以,我需要select
每个原材料的最后3个动作
我有这个查询但不起作用
SELECT a.*, b.price, b.created
FROM raw_materials a
LEFT JOIN
(SELECT price, raw_material_id, created FROM raw_material_moves ORDER BY created DESC LIMIT 3) b
ON b.raw_material_id=a.id
ORDER BY a.id
答案 0 :(得分:1)
我主要同意@chetan对变量的使用来完成这项工作。
Here is one of the best articles我在这个问题上遇到了不同的处理方式......从简单到难以理解。
答案 1 :(得分:0)
我建议您使用DESC(或)以相反的顺序提取用户光标
答案 2 :(得分:0)
SELECT r1.id,name,raw_material_id
FROM raw_materials r1, raw_materials_move r2
WHERE r1.id=r2.id ORDER BY DESC LIMIT 3;
答案 3 :(得分:0)
最后3个按每个原材料的创建(我假设日期)移动
select * from
(select a.id,a.price,a.created,
if(@mat=a.raw_material_id,@num:=@num+1,@num:=1) rank,
@mat:=a.raw_material_id
from raw_materials_moves a, (select @num:=0) b
order by a.raw_material_id,a.created desc) temp
where rank <=3;
请参阅demo here
答案 4 :(得分:-3)
对其进行反向排序(即... SORT BY somefield DESC
),然后获得前3个(通过附加LIMIT 3
)