如何使用MySQL选择父/子关系中最后一行与条件匹配的最后一个子行
我问了一个类似于a的问题 他的问题是:“仅使用MySQL,我想选择父子关系的最后一个子行,其中子行按时间戳排序” 我希望这样做,但是我也希望只选择如何使用MySQL选择父/子关系中最后一行与条件匹配的最后一个子行,mysql,sql,Mysql,Sql,我问了一个类似于a的问题 他的问题是:“仅使用MySQL,我想选择父子关系的最后一个子行,其中子行按时间戳排序” 我希望这样做,但是我也希望只选择状态为1的子行 我的表格是fobs\u inventory和fobs\u inventory\u history。我想要每个fobs\u库存的最新(即:最近时间戳)记录fobs\u库存历史,其中fobs\u库存历史。status=1 ------------------------------- | fobs_inventory
状态为1的子行
我的表格是fobs\u inventory
和fobs\u inventory\u history
。我想要每个fobs\u库存
的最新(即:最近时间戳)记录fobs\u库存历史
,其中fobs\u库存历史。status=1
-------------------------------
| fobs_inventory |
-------------------------------
| inv_id | other fields |
-------------------------------
| 1 | ... |
| 2 | ... |
| 3 | ... |
-------------------------------
----------------------------------------------
| fobs_inventory_history |
----------------------------------------------
| id | inv_id | status | created_at |
----------------------------------------------
| 1 | 1 | 0 | 2011-10-11 10:00:00 |
| 2 | 1 | 1 | 2011-08-01 10:00:00 |
| 3 | 1 | 0 | 2011-07-01 10:00:00 |
| 4 | 2 | 1 | 2011-09-11 14:00:00 |
| 5 | 2 | 0 | 2011-08-01 12:00:00 |
| 6 | 2 | 2 | 2011-07-01 00:00:00 |
| 7 | 3 | 1 | 2011-10-11 14:00:00 |
| 8 | 3 | 2 | 2011-08-01 12:00:00 |
| 9 | 3 | 0 | 2011-07-01 00:00:00 |
----------------------------------------------
生成类似下表的结果集的最佳SQL语法是什么
--------------------------------------------------------------------
| inv_id | fob_inventory_history_id | status | created_at |
--------------------------------------------------------------------
| 2 | 4 | 1 | 2011-09-11 14:00:00 |
| 3 | 7 | 1 | 2011-10-11 14:00:00 |
--------------------------------------------------------------------
我只想返回那些最近的时间戳状态为1的行
编辑
在做了更多的工作之后,我提出了我在这里发布的解决方案,因为它可能会帮助其他人尝试做同样的事情
基本上,解决方案是选择与MAX()和GROUP BY关联的所有对应字段,在子选择之外,将其签出:
select h.id, h.fob_id, h.inv_id, h.status, h.created_at from fobs_inventory_history h, (
select id, inv_id, status, max(created_at) as ts
from fobs_inventory_history
group by inv_id
) h2
where h.created_at = h2.ts
and h.inv_id = h2.inv_id
and h.fob_id = 1 and h.status = 1
试一试
您可以根据要获取的行数修改限制非常感谢您发布此消息!!它解决了一个我坚持了两天的问题。
我需要包含一些父信息,因此我向该查询添加了一个联接,如下所示:
select i.custid, i.custorderno, h.id, h.fob_id, h.inv_id, h.status, h.created_at from fobs_inventory_history h, (
select id, inv_id, status, max(created_at) as ts
from fobs_inventory_history
group by inv_id
) h2
INNER JOIN invoice AS i ON h2.inv_id = i.inv_id
where h.created_at = h2.ts
and h.inv_id = h2.inv_id
and h.fob_id = 1 and h.status = 1
select i.custid, i.custorderno, h.id, h.fob_id, h.inv_id, h.status, h.created_at from fobs_inventory_history h, (
select id, inv_id, status, max(created_at) as ts
from fobs_inventory_history
group by inv_id
) h2
INNER JOIN invoice AS i ON h2.inv_id = i.inv_id
where h.created_at = h2.ts
and h.inv_id = h2.inv_id
and h.fob_id = 1 and h.status = 1