我有这样的查询:
SELECT pov.product_id
, (SELECT AVG(r1.rating) AS total
FROM oc_review r1
WHERE r1.product_id = pov.product_id
AND r1.status = 1
GROUP
BY r1.product_id) AS rating
, (SELECT price
FROM oc_product_special ps
WHERE ps.product_id = pov.product_id
AND ps.customer_group_id = 1
AND (
(ps.date_start = '0000-00-00' OR ps.date_start < NOW())
AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())
)
ORDER
BY ps.priority ASC
, ps.price ASC
LIMIT 1
) AS special
FROM oc_product_option_value pov
LEFT
JOIN oc_product_to_category p2c
ON pov.product_id = p2c.product_id
LEFT
JOIN oc_product p
ON p.product_id = pov.product_id
LEFT
JOIN oc_product_special ps
ON ps.product_id = pov.product_id
WHERE p2c.category_id = 62
AND pov.option_id = 13
AND pov.quantity > 0
ORDER
BY p.date_added DESC
LIMIT 54
如果我不使用LIMIT,则我的查询有200多个结果,但是当我限制54个结果时,我的查询有21个结果。为什么?在验证表中的条件而不是第一选择的总和后,我该如何限制结果?
答案 0 :(得分:1)
这是Opencart数据库。您的尝试有多个问题。
product_option_value
将为option_value_id
具有多个product_id
值。您需要使用Distinct
才能获得独特的产品。oc_product
上进行左联接,因为如果没有product_option_value_id
表中的product_id
,那么oc_product
就不会存在。category_id
上进行搜索,因此您也可以将left join
表上的oc_product_to_category
更改为inner join
。尝试:
SELECT DISTINCT pov.product_id
, (SELECT AVG(r1.rating) AS total
FROM oc_review r1
WHERE r1.product_id = pov.product_id
AND r1.status = 1
GROUP
BY r1.product_id) AS rating
, (SELECT price
FROM oc_product_special ps
WHERE ps.product_id = pov.product_id
AND ps.customer_group_id = 1
AND (
(ps.date_start = '0000-00-00' OR ps.date_start < NOW())
AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())
)
ORDER
BY ps.priority ASC
, ps.price ASC
LIMIT 1
) AS special
FROM oc_product_option_value pov
INNER
JOIN oc_product_to_category p2c
ON pov.product_id = p2c.product_id
INNER
JOIN oc_product p
ON p.product_id = pov.product_id
LEFT
JOIN oc_product_special ps
ON ps.product_id = pov.product_id
WHERE p2c.category_id = 62
AND pov.option_id = 13
AND pov.quantity > 0
ORDER
BY p.date_added DESC
LIMIT 54