获取项目的最后状态

时间:2010-07-19 08:06:25

标签: mysql group-by greatest-n-per-group

在MySQL中,我有两个表与1:n的关系。

表项目包含产品,其状态保存在另一个表中,如下所示:

项目:

id |ref_num|name    |...
1  |0001   |product1|...
2  |0002   |product2|...

items_states:

id|product_id|state_id|date
1 |1         |5       |2010-05-05 10:25:20
2 |1         |9       |2010-05-08 12:38:00
3 |1         |6       |2010-05-10 20:45:12
...

states表不相关,只关联state_id和州名等等。

如何获得最新状态是我指定的状态的产品,每行一个项目?

谢谢

2 个答案:

答案 0 :(得分:1)

您可能需要尝试以下操作:

SELECT i.ref_num, i.name, s.latest_date
FROM   items i
JOIN   (
           SELECT   product_id, MAX(date) as latest_date
           FROM     items_states
           GROUP BY product_id
       ) s ON (s.product_id = i.id);

如果您只想返回一个项目,只需在查询中添加WHERE i.id = ?

测试用例:

CREATE TABLE items (id int, ref_num varchar(10), name varchar(10));
CREATE TABLE items_states (id int, product_id int, state_id int, date datetime);

INSERT INTO items VALUES (1, '0001', 'product1');
INSERT INTO items VALUES (2, '0002', 'product2');

INSERT INTO items_states VALUES (1, 1, 5, '2010-05-05 10:25:20');
INSERT INTO items_states VALUES (2, 1, 9, '2010-05-08 12:38:00');
INSERT INTO items_states VALUES (3, 1, 6, '2010-05-10 20:45:12');

结果:

+---------+----------+---------------------+
| ref_num | name     | latest_date         |
+---------+----------+---------------------+
| 0001    | product1 | 2010-05-10 20:45:12 |
+---------+----------+---------------------+
1 row in set (0.02 sec)

答案 1 :(得分:0)

LEFT将items_states表连接到自身,需要second.date> first.date,并在其中放入一个WHERE second.id IS NULL子句:

SELECT a.* 
FROM item_states a 
LEFT JOIN item_states b
ON a.product_id = b.product_id
AND b.product_id > a.product_id
WHERE b.id IS NULL AND a.state_id = <desired state>

或制作基于行的查询:请参阅Mark Byers'示例。