mysql限制子查询非主体查询

mbjcgjjk  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(315)

我有这样一个问题:

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个结果。为什么?如何在验证表中的条件(而不是第一次选择的总计)之后限制结果?

v1l68za4

v1l68za41#

这是opencart数据库。您的尝试有多个问题。 product_option_value 将有多个 option_value_id a的值 product_id . 你需要使用 Distinct 获得独特的产品。
你不需要做左联合 oc_product 自从 product_option_value_id 没有你就不能存在 product_idoc_product table。
既然你在搜索 category_id ,您也可以更改 left joinoc_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

相关问题