0
我有2個表:獲取最後的成本爲每行
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
我想去年的成本資料。 這樣的:
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
現在我剛剛得到的材料清單,並獲得在PHP foreach循環費用(+1查詢的每一行)
請幫助我!
我不認爲這是從描述和缺乏數據集提供確切負責。 – Strawberry