【问题标题】:Get last state of item获取项目的最后状态
【发布时间】:2010-07-19 08:06:25
【问题描述】:

在 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
...

状态表不相关,仅将 state_id 与状态名称相关联。

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

谢谢

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

      【解决方案2】:

      要么将 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' 示例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-10
        • 2018-10-28
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多