【发布时间】:2017-12-05 01:02:20
【问题描述】:
我有 3 张桌子
price_history (Primary: id)
+----+------------+------+---------+-------+------------+
| id | id_product | sku | id_shop | price | date_add |
+----+------------+------+---------+-------+------------+
| 1 | 11 | 101 | 1001 | 10 | 2017-07-01 |
| 2 | 12 | 101 | 1002 | 15 | 2017-07-01 |
| 3 | 13 | 101 | 1003 | 20 | 2017-07-01 |
| 4 | 11 | 101 | 1001 | 11 | 2017-07-02 | <-- lowest latest
| 5 | 14 | 102 | 1001 | 45 | 2017-07-01 |
| 6 | 15 | 102 | 1002 | 45 | 2017-07-01 |
| 7 | 16 | 102 | 1003 | 45 | 2017-07-01 | <-- shop 1003 is the lowest,
latest among shops and should not be display, because the shop monitored is 1001
| 8 | 15 | 102 | 1002 | 60 | 2017-07-02 |
| 9 | 14 | 102 | 1001 | 55 | 2017-07-02 |
|10 | 17 | 103 | 1001 | 90 | 2017-07-01 |
|11 | 18 | 103 | 1002 | 90 | 2017-07-01 |
|12 | 19 | 103 | 1003 | 90 | 2017-07-01 |
|13 | 17 | 103 | 1001 | 100 | 2017-07-02 | <-- lowest latest
|14 | 18 | 103 | 1002 | 100 | 2017-07-02 |
|15 | 19 | 103 | 1003 | 100 | 2017-07-02 |
+----+------------+------+---------+-------+------------+
product (primary: id_product)
+------------+---- ---+-----+--------------+---------+
| id_product | active | sku | product_name | id_shop |
+------------+--------+-----+--------------+---------+
| 11 | 1 | 101 | Red | 1001 |
| 12 | 1 | 101 | A bit red | 1002 |
| 13 | 1 | 101 | Very red0 | 1003 |
| 14 | 1 | 102 | Blue | 1001 |
| 15 | 1 | 102 | A bit blue | 1002 |
| 16 | 1 | 102 | Very blue | 1003 |
| 17 | 1 | 103 | Green | 1001 |
| 18 | 1 | 103 | A bit green | 1002 |
| 19 | 1 | 103 | Very green | 1003 |
| 20 | 0 | 104 | Discontinued | 1001 |
| 21 | 0 | 104 | Out of stock | 1002 |
| 22 | 0 | 104 | Varnish | 1003 |
+------------+--------+-----+--------------+---------+
shop (primary: id_shop)
+---------+--------+
| id_shop | name |
+---------+--------+
| 1001 | Shop A |
| 1002 | Shop B |
| 1003 | SHop C |
+---------+--------+
每家商店都有不同的产品名称,但都有国际编号 (sku)。
要监控的 ID 店铺:1001(店铺 A)
已经在 stackoverflow 中搜索,但我找不到正确的。 我怎样才能获得每个 sku 的最低和最新价格。 我还是新手,不懂子选择
这是我目前所做的
SELECT pph.id, s.name, h2.price, h2.sku
FROM (
SELECT MAX(h.id) max_id, MIN(h.price) min_price, h.id, h.id_shop
FROM price h
GROUP BY sku
) pph
LEFT JOIN price h2 ON (h2.id = max_id)
LEFT JOIN shop s ON (s.id_shop = pph.id_shop)
那么最后我只需要显示被监控的商店,'Shop A'
预期结果:
+----+------------+------+---------+-------+
| id | id_product | sku | id_shop | price |
+----+------------+------+---------+-------+
| 4 | 11 | 101 | 1001 | 11 |
|13 | 17 | 103 | 1001 | 100 |
+----+------------+------+---------+-------+
sku 102的最低价格是shop 1003,所以我们不需要展示他们。
JSFiddle http://sqlfiddle.com/#!9/ba3a2
谢谢
需要帮助,仍未找到解决方案
【问题讨论】:
-
也显示您的预期结果
-
@JYoThI 预期结果已添加
-
@Gurwinder Singh 是的,你是对的。
date_add已添加 -
@Gurwinder Singh 第二个标志 102
<-- lowest latest已更正。你的眼睛像鹰一样锐利......