如何选择父/子关系的最后一个子行,其中最后一行与使用MySQL的条件匹配

时间:2011-09-15 11:56:06

标签: mysql sql

我的问题类似于previous poster

他的问题是:“仅使用MySQL我想选择父子关系的最后一个子行,其中子行按时间戳排序”。

我想这样做,但我还想只选择status为1的子行。

我的表格为fobs_inventoryfobs_inventory_history。我想要每个fobs_inventory_history的最新(即:最近时间戳)fobs_inventory记录,其中fobs_inventory_history.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 |
--------------------------------------------------------------------

我想只返回最新时间戳为status为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

2 个答案:

答案 0 :(得分:1)

非常感谢你发帖!它解决了我被困两天的问题。 我需要包含一些父信息,所以我在这个查询中添加了一个JOIN,如下所示:

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

答案 1 :(得分:0)

尝试

select 
   inv_id, id AS fob_inventory_history_id, status, created_at from  fobs_inventory_history 
where
   status = 1
order by created_at desc
LIMIT 2

您可以根据要提取的行数修改限制