mysql 根据两个标准进行选择
我有点赶时间,所以我知道我可以自己寻找答案,但 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 始终是最近的更改,
非常感谢!
I'm a little rushed for time so I know I could look for the answer myself but stackoverflow is faster! :)
I have a table with data let's pretend it is product information. the table keeps track of when the product data is updated. If I run a query like
SELECT * FROM productChangeLog where change = 'price changed'
I get results like
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'
what I want to do is select only the most recent 'price change' for each product. what do I need to add to my query so that i would only get row 241 and 512? the higher id is always the more recent change
thanks so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
GROUP BY 键字段并使用 HAVING 子句提取记录。
对于您的情况,您可以尝试,
OR
这些在标准 SQL 中是非法查询,但在 MySQL 中应该可以工作。
顺便说一句,您的结果如何显示第 242 行和第 517 行“描述已更改”?
GROUP BY the key-fields and use HAVING clause to extract the record.
In your case, you may try,
OR
These are illegal queries in standard SQL, but should work in MySQL.
BTW, how is your result showing row 242 and 517 with 'description changed'?
这种方法完成同样的事情,但使用 ANSI 语法,并且可以扩展以合并多个字段:
如果 { Group, Date } 不唯一,则只需要多一点代码:
This approach accomplishes the same thing, but uses ANSI syntax and can be extended to incorporate multiple fields:
If { Group, Date } is not unique, you need just a little more code: