MySQL选择具有唯一属性值的一行

时间:2013-09-16 10:42:54

标签: mysql sql database

我正在建立一个库存系统并决定将每个产品的余额(每次更新时)存储到下表中:

+------------+--------------+---------+------+
| Product_id | Warehouse_id | Balance | Date |
+------------+--------------+---------+------+

示例:

员工在仓库_id 5中的product_id 123中添加10件

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 123        | 5            | 10      | 2013-09-16  |
+------------+--------------+---------+-------------+

然后,工作人员在仓库5中的产品234中添加3件,并且 仓库5中的5件到123件,

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 123        | 5            | 10      | 2013-09-16  |
| 234        | 5            | 3       | 2013-09-18  |
| 123        | 5            | 15      | 2013-09-21  |
+------------+--------------+---------+-------------+

*注意日期栏

现在让我再添加几行

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 123        | 5            | 10      | 2013-09-16  |
| 234        | 5            | 3       | 2013-09-18  |
| 123        | 5            | 15      | 2013-09-21  |
| 123        | 5            | 18      | 2013-09-24  |
| 234        | 5            | 10      | 2013-09-26  |
| 123        | 5            | 22      | 2013-09-29  |
+------------+--------------+---------+-------------+

如何在2013年9月25日运行能够获得所有产品余额的查询?

这意味着我需要以下结果:

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 234        | 5            | 3       | 2013-09-18  |
| 123        | 5            | 18      | 2013-09-24  |
+------------+--------------+---------+-------------+

简而言之,我需要每个product_id的最新行(按日期)。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

假设每个仓库维护产品的余额,您可以这样做

SELECT t.product_id, t.warehouse_id, t.balance, t.date
  FROM table1 t JOIN 
(
  SELECT warehouse_id, product_id, MAX(date) date
    FROM table1
   WHERE date <= '2013-09-25'
   GROUP BY warehouse_id, product_id
) q
    ON t.warehouse_id = q.warehouse_id
   AND t.product_id = q.product_id
   AND t.date = q.date

输出:

| PRODUCT_ID | WAREHOUSE_ID | BALANCE |       DATE |
|------------|--------------|---------|------------|
|        234 |            5 |       3 | 2013-09-18 |
|        123 |            5 |      18 | 2013-09-24 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

SELECT * 
FROM TABLE 
WHERE (PRODUCT_ID, DATE) IN
     (SELECT PRODUCT_ID, MAX(DATE) FROM TABLE
      WHERE DATE <= '2013-09-25'     
       GROUP BY PRODUCT_ID )

答案 2 :(得分:0)

查询:

<强> SQLFIDDLEExample

  SELECT *
  FROM table1 t 
  WHERE t.`Date` = (SELECT MAX(t2.`Date`)
                  FROM Table1 t2
                  WHERE t2.`Date` <= '2013-09-25'
                  AND t2.product_id = t.product_id)