我有 2 张 table :
materials:
int id
text title
costs:
int id
int material_id
int cost
datetime created_at
数据:
materials:
1 Wood
2 Steel
3 ...
costs:
1,1,200,2015-07-02
2,1,205,2015-07-03
3,1,210,2015-07-04
我想获得最新成本的 Material 。 像这样:
id title cost
1 Wood 210
我试试这个:
select materials.id, title, cost from materials
left join (
select * from costs
order by costs.id DESC
) as costs on costs.material_id = materials.id
group by materials.id
还有这个:
select materials.id, materials.title, c1.cost from costs c1
join (select material_id, max(id) as id from costs group by material_id) AS c2
on c1.id = c2.id
left join materials on materials.id = c1.material_id
但成本有时(!)不正确。
这会返回一个值的正确成本:
select cost, material_id
from costs
where material_id = 2
order by id DESC
limit 1
现在我只是获取 Material 列表并在 php foreach 循环中获取成本(每行+1 个查询)
请帮帮我!
最佳答案
select m.id, m.title, c1.cost
from materials m
join costs c1 on c1.material_id = m.id
join
(
select material_id, max(created_at) as dt
from costs
group by material_id
) c2 on c2.material_id = m.id and c2.dt = c1.created_at
关于php - 获取每行的最后成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31371484/