我有一个包含两个表的数据库。一个保存项目数据,另一个保存表中项目的价格统计。
项目表itemid(整数,自动递增)|名称(varchar)|说明(varchar)| add_on(日期时间)
统计信息表:id(int,自动递增)|项目(整数)|价格(整数)| date_seen(datetime)
第一个表中的'itemid'列是唯一的,在第二个表中被称为'item'。每次检查价格时,如果价格从上次更改后,它就会被添加到统计表中。 d已检查
作为示例,表如下所示:
Item Table
itemid (int, auto increment) | name (varchar) | description (varchar) | added_on (datetime)
1 | testproduct1 | This is a testproduct | 2020-04-23 16:43:47
2 | testproduct2 | This is a testproduct too | 2020-04-23 17:08:32
stats table:
id (int, auto increment) | item (int) | price (int) | date_seen ( datetime )
1 | 1 | 7 | 2020-04-23 09:12:00
2 | 1 | 4 | 2020-04-23 09:34:00
3 | 2 | 8 | 2020-04-23 09:12:00
4 | 2 | 6 | 2020-04-23 09:34:00
5 | 1 | 3 | 2020-04-23 10:08:00
6 | 2 | 4 | 2020-04-23 10:08:00
让我们今天添加一个Top5项,按last_seen DESC排序,然后按价格DESC排序,这样您将获得以下输出:
NAME |PRICE| date_seen
testproduct2 | 4 | 2020-04-23 10:08:00
testproduct1 | 3 | 2020-04-23 10:08:00
我将如何处理?我尝试了以下]]
SELECT * FROM ( SELECT i.itemid, i.name, s.price, s.date_seen AS sdate, FROM items i INNER JOIN stats s ON i.itemid = s.item WHERE i.added_on LIKE '2020-04-23%' ) AS sub ORDER BY `sub`.`sdate` DESC,`sub`.`price` DESC GROUP BY i.itemid
但是,这里似乎不允许group by,没有它,查询将起作用,我得到的结果是按日期排序的,但是价格根本没有排序。什么是获得所需结果的正确查询?预先感谢!
我有一个包含两个表的数据库。一个保存项目数据,另一个保存表中项目的价格统计。项目表itemid(整数,自动递增)|名称(varchar)|说明(...
您可以使用子查询来过滤每个项目的最新stats
记录:
您在末尾的内部句号中有一个逗号,就这么多了>
和GROUP BY必须到之前