mysql根据两个标准选择

时间:2011-05-05 20:51:35

标签: mysql sql multiple-select

我有点匆忙,所以我知道我可以自己寻找答案但是stackoverflow更快! :)

我有一个数据表让我们假装它是产品信息。该表记录产品数据的更新时间。如果我运行像

这样的查询
SELECT * FROM productChangeLog where change = 'price changed'

我得到的结果如

id  product  date       change
---------------------------------------------    
236 product1 03/14/2011 'price changed'    
241 product2 03/14/2011 'price changed'    
242 product2 03/14/2011 'description changed'    
512 product1 05/16/2011 'price changed'    
517 product1 05/16/2011 'description changed'

我想要做的只是为每种产品选择最近的“价格变动”。我需要添加到我的查询中,以便我只获得第241行和第512行?较高的ID始终是最近的更改

非常感谢!

3 个答案:

答案 0 :(得分:2)

SELECT t.max_id, t.product, pcl.date, pcl.change
    FROM (SELECT product, MAX(id) AS max_id
              FROM productChangeLog 
              WHERE change = 'price changed'
              GROUP BY product) t
        INNER JOIN productChangeLog pcl
            ON t.max_id = pcl.id

答案 1 :(得分:0)

GROUP BY键字段并使用HAVING子句提取记录。

在您的情况下,您可以尝试,

-- Don't use this if the product data can be updated twice on
-- the same day since the date field doesn't have a timestamp
SELECT * FROM productChangeLog where change = 'price changed' 
GROUP BY product HAVING MAX(date) = date

OR

-- Assuming the id is an integer field, this might be faster
SELECT * FROM productChangeLog where change = 'price changed' 
GROUP BY product HAVING MAX(id) = id

这些是标准SQL中的非法查询,但应该可以在MySQL中使用。

顺便说一下,你的结果如何显示第242行和第517段“描述已更改”?

答案 2 :(得分:0)

这种方法完成了同样的事情,但使用了ANSI语法,可以扩展为包含多个字段:

SELECT
  *
FROM
  Table AS T1
WHERE
  NOT EXISTS
    (
    SELECT * FROM Table AS T2 WHERE T1.Group = T2.Group AND T2.Date < T1.Date
    )

如果{Group,Date}不是唯一的,则只需要更多代码:

SELECT
  *
FROM
  Table AS T1
WHERE
  NOT EXISTS
    (
    SELECT * FROM Table AS T2 WHERE T1.Group = T2.Group AND (T2.Date < T1.Date OR (T1.Date = T2.Date AND T2.ID < T1.ID))
    )