我尝试获得每种最新和最低报价的产品清单
表格产品:
id | name
表格提供:
id | product_id | price | created | dealer_id
表格残留:
id | offer_id | status
我试过了:
SELECT * FROM product INNER JOIN
(
SELECT offer.product_id , offer.price
FROM offer
LEFT JOIN invalids
ON offer.id = invalids.offer_id
WHERE invalids.id IS NULL
GROUP BY offer.dealer_id
ORDER BY offer.created DESC
) o
ON o.product_id = product.id
ORDER BY product.name
我尝试了一个带有此优惠价值的sqlfiddle http://sqlfiddle.com/#!9/32658/3:
(`id`, `price`, `dealer_id`, `product_id`, `created`)
(1,12.60,1,1,'2015-05-17 08:44:45'),
(2,13.00,1,1,'2015-08-17 08:44:45'),
(3,20.00,1,1,'2015-08-17 08:45:30'),
(4,10.00,1,1,'2015-08-17 08:45:46'),
(5,4.00,2,1,'2015-05-17 08:44:11'),
(6,11.00,2,1,'2015-08-17 08:44:46'),
(7,5.00,2,1,'2015-08-17 08:45:31'),
(9,110.00,2,2,'2015-08-17 08:46:58'),
(10,11.00,2,2,'2015-08-17 08:47:12');
产品ID 1的预期价值为商品ID 7,价格为5.
我认为我必须意识到这些步骤:
created
订阅优惠,按dealer_id
分组以获取最新条目也许我必须在SELECT FROM offer
和GROUP BY
使用第二个ORDER BY
,但如何从第一个(外部)选择中获取product_id
?
答案 0 :(得分:0)
此查询可以帮助您:
SELECT *
FROM product
JOIN (
SELECT product_id, min(price) as minPrice, max(created) as newestOffer
FROM offer
WHERE id NOT IN (SELECT offer_id FROM invalids)
GROUP BY 1
) as b
ON product.id = b.product_id
答案 1 :(得分:0)
那么我首先要获得每个产品的最新日期:
SELECT product_id, MAX(created) AS latestOffer
FROM offer
GROUP BY product_id;
完成后,您可以将其加入原始表格以获得该优惠:
SELECT o.*
FROM offer o
JOIN(
SELECT product_id, MAX(created) AS latestOffer
FROM offer
GROUP BY product_id) tmp ON tmp.product_id = o.product_id AND tmp.latestOffer = o.created;
这是一个SQL Fiddle示例。
答案 2 :(得分:0)
根据我的理解,在黑暗中拍摄......
许多嵌套的子查询..继续思考,必须有更好的方法......
SELECT OO.ID, OO.Price, OO.Dealer_Id, OO.Product_ID, OO.created, P.name
FROM Offer OO
INNER JOIN (
SELECT Min(Price) as MinP
FROM offer O
INNER JOIN (
SELECT max(OI.created) as LatestOffer, OI.Dealer_ID, OI.Product_ID
FROM Offer OI
LEFT JOIN invalids I
on OI.Id = I.offer_Id
WHERE I.ID is null
GROUP BY OI.Dealer_Id, OI.Product_Id
) B
on O.Dealer_Id = B.Dealer_Id
and O.Product_Id = B.Product_Id
and O.Created = B.LatestOffer
) Z
on OO.Price = Z.MinP
INNER JOIN product P
on P.ID = OO.Product_ID