使用group by查询两个db并显示详细信息

时间:2012-03-21 09:08:41

标签: mysql

我有两张桌子 1:itemInfo

product_id  brand   name    category 
1   Garden  Goodcake    cake

2:itemRecord

record_id shopType price inputTime product_id       
1   0   7.2     2012-03-20 17:58:56 1
69  2   6.4     2012-03-20 19:33:12 1
70  0   9.9     2012-03-19 00:00:00 1
71  3   5.5     2012-03-18 05:22:00 1
72  0   6.8     2012-03-19 20:26:29 1
73  0   10.1    2012-03-17 12:27:00 1
74  3   7.9     2012-03-16 00:00:00 1
75  1   6.7     2012-03-15 00:00:00 1
76  1   8.8     2012-03-14 11:24:00 1
77  2   12.5    2012-03-13 10:26:19 1
78  0   7.2     2012-03-21 11:25:23 1   
146 2   5       2012-03-21 12:53:04 1
149 3   4.9     2012-03-21 10:00:00 1
150 3   5.1     2012-03-21 12:20:00 1

我想显示最近7天的最低价product_id = 1。 如果在同一天,最便宜的价格是相同的,只需显示最新的。
决赛桌应该是:

product_id brand   name     category inputTime  shopType minimum_price record_id
1          Garden  Goodcake cake     2012-03-21 3        4.9           149
1          Garden  Goodcake cake     2012-03-20 2        6.4           69
1          Garden  Goodcake cake     2012-03-19 2        6.8           72
...
1          Garden  Goodcake cake     2012-03-15 1        6.7           75

我尽力写一个喜欢的SQL:

SELECT r.product_id, i.brand, i.name, i.category, DATE_FORMAT( r.inputTime, '%e-%b' ) AS inputTime, r.shopType, MIN( r.price ) AS minimum_price, r.record_id
FROM itemRecord AS r, itemInfo AS i
WHERE r.product_id = '1'
AND i.id = r.product_id
GROUP BY DATE( r.inputTime ) DESC
LIMIT 0 , 7

但是,表格是:

product_id  brand   name    category    inputTime   shopType    minimum_price   record_id
1   Garden  Goodcake cake       21-Mar  0   4.9     78
1   Garden  Goodcake cake       20-Mar  0   6.4     1
1   Garden  Goodcake cake       19-Mar  0   6.8     70
1   Garden  Goodcake cake       18-Mar  3   5.5     71
1   Garden  Goodcake cake       17-Mar  0   10.1    73
1   Garden  Goodcake cake       16-Mar  3   7.9     74
1   Garden  Goodcake cake       15-Mar  1   6.7     75

例如,第一行结果,它显示正确的最低价格4.9,但是record_id是错误的,同样,shopType也是错误的。
我有很多研究,但仍然无法解决问题 请帮忙......

1 个答案:

答案 0 :(得分:2)

加入他们:

SELECT r.product_id, i.brand, i.name, i.category, DATE_FORMAT( r.inputTime, '%e-%b' ) AS inputTime, r.shopType, r.price AS minimum_price, r.record_id
FROM (  SELECT *
        FROM itemRecord
        WHERE product_id = '1'
        ORDER BY price ASC, inputTime DESC) AS r
INNER JOIN itemInfo As i
ON r.product_id = i.product_id
WHERE i.id = r.product_id
GROUP BY DATE(r.inputTime)
LIMIT 0, 7

<强>解释

我执行内部查询,按price ASC而不是默认值呈现表格顺序,让我们说id ASC。当您GROUP BY行时,它会默认使用第一行中的列,在这种情况下是最低价格的列。

您的解决方案无效,因为它可能还选择了第一个ID,而不是最低价格行。唯一正确的列是MIN(r.price),但是您注意到该函数不会影响结果中的其他列。