php - 获取每行的最后成本

标签 php mysql

我有 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/

相关文章:

mysql - 在 MySQL 数据库中跟踪每个用户的 "blocked users"的最有效方法是什么?

php - 从 mysql_* 转换为 mysqli 抛出 "Can' t 连接到 'host_name' 上的 MySQL 服务器“

php - 从 php 页面启动在服务器上运行的 php 脚本(并打开套接字)

javascript - 如何从 XML 获取多个节点元素类型到一个变量中

java - 通信链路失败 : Spring boot, MySQL、Docker

php - 移动VPS服务器后,PHP无法正常工作

MySQL加载数据到文件json数组

php - 是否可以通过 1 个 SQL 查询(而不是 30 个)来完成?

php - 与 ADODB 的 SSL 连接

php - 模型中 1 个函数中的多个 MySQL 查询