我尝试获取最新创建的产品价格。每个产品都是独一无二的,但价格可能不同。但是,仅当产品的价格超过product_price表中的行时,我的查询才有效:
这是我的疑问:
SELECT
i.name AS title,
i.id AS product_id,
m.name AS manufacturer,
image,
price_sales,
price_new,
price_used,
price_old
FROM product_info as i
LEFT JOIN product_manufacturer AS m ON i.manufacturer_id = m.id
LEFT JOIN (SELECT * FROM product_price ORDER BY created_at DESC LIMIT 1) AS p ON i.id = p.id_product
WHERE category_id = 2
AND i.is_deactivated IS NULL
LIMIT 0, 20;
我只需要最新创建的价格行。
答案 0 :(得分:1)
你遇到的问题是子查询:
(SELECT * FROM product_price ORDER BY created_at DESC LIMIT 1)
没有获得每件产品的最新价格,只是最新的价格,因此只返回一行,这意味着只有一件产品实际上会有价格。
解决此问题的方法是删除存在较新价格的任何价格,因此为简单起见,如果仅查看价格表,以下内容仅为您提供最新产品价格:
SELECT p.*
FROM product_price AS p
WHERE NOT EXISTS
( SELECT 1
FROM product_price AS p2
WHERE p2.id_product = p.id_product
AND p2.created_at > p.created_at
);
然而,MySQL will optmise LEFT JOIN/IS NULL
better than NOT EXISTS
(虽然我认为前者表达的意图更好),所以更有效的方法是:
SELECT p.*
FROM product_price AS p
LEFT JOIN product_price AS p2
ON p2.id_product = p.id_product
AND p2.created_at > p.created_at
WHERE p2.id IS NULL;
最后,将此介绍回主要查询,最终会得到:
SELECT i.name AS title,
i.id AS product_id,
m.name AS manufacturer,
i.image,
p.price_sales,
p.price_new,
p.price_used,
p.price_old
FROM product_info as i
LEFT JOIN product_manufacturer AS m
ON m.id = i.manufacturer_id
LEFT JOIN product_price AS p
ON p.id_product = i.id
LEFT JOIN product_price AS p2
ON p2.id_product = p.id_product
AND p2.created_at > p.created_at
WHERE i.category_id = 2
AND i.is_deactivated IS NULL
AND p2.id IS NULL
LIMIT 0, 20;