Mysql 问题分组?

Mysql 问题分组?,mysql,Mysql,有人能帮我做这个吗 这是我的表格结构: rec_id product_id quantity quantity_in quantity_out balance stock_date status 1 2 342 NULL 17 325 2009-10-23 1 2 2 325 NULL 124 20

有人能帮我做这个吗

这是我的表格结构:

rec_id product_id quantity quantity_in quantity_out balance stock_date status 1 2 342 NULL 17 325 2009-10-23 1 2 2 325 NULL 124 201 2009-10-23 1 3 1 156 NULL 45 111 2009-10-23 1 4 2 201 NULL 200 1 2009-10-23 1 5 2 1 NULL 1 0 2009-10-23 1 6 1 111 NULL 35 76 2009-10-23 1
谢谢

您可以找到每种产品的最新记录,如:

select max(rec_id) as MaxRec
from YourTable
group by product_id
使用子查询,可以检索其产品的最新行:

select *
from YourTable
where rec_id in (
    select max(rec_id) as MaxRec
    from YourTable
    group by product_id
)

这里有一个没有子查询的单个查询:

SELECT main.*
FROM YourTable main
LEFT JOIN YourTable newer
    ON newer.product_id = main.product_id AND newer.rec_id > main.rec_id
WHERE newer.rec_id IS NULL;

您可以随意调整字段列表--确保从main中选择字段,而不是较新的字段,字段应全部为空。

请更清楚地了解您的预期结果…按产品id将其显示为table resultwant Recents records group by product_id,以便我只获得产品的一条记录。在上述6条记录中,对于产品id“1”,最近的记录是rec_id 5,对于产品id“2”,最近的记录是rec_id 6
SELECT main.*
FROM YourTable main
LEFT JOIN YourTable newer
    ON newer.product_id = main.product_id AND newer.rec_id > main.rec_id
WHERE newer.rec_id IS NULL;