SELECT产品变体SQL

时间:2017-02-24 12:17:46

标签: php sql

这是我没有变体选项的查询

SELECT p.*, pd.`name` AS `product_name`
FROM `product` AS `p`  
LEFT JOIN `product_description` AS `pd` ON p.`id` = pd.`product_id` 
LEFT JOIN `product_to_variant` AS `pv` ON p.`id` = pv.`product_id`
WHERE p.`status` = 0
GROUP BY p.`id`
ORDER BY p.`id` DESC;

SQLFiddle:http://sqlfiddle.com/#!9/8955b/5

并且后续查询具有变体选项,但它不起作用

SELECT p.*, pd.`name` AS `product_name`
FROM `product` AS `p`  
LEFT JOIN `product_description` AS `pd` ON p.`id` = pd.`product_id` 
LEFT JOIN `product_to_variant` AS `pv` ON p.`id` = pv.`product_id`
WHERE p.`status` = 0
    AND (pv.`feature_id` = 2 AND pv.`variant_id` = 6)
    AND (pv.`feature_id` = 3 AND pv.`variant_id` = 11)
GROUP BY p.`id`
ORDER BY p.`id` DESC;

我也试图查询,但没有输出

SELECT pv.* FROM `product_to_variant` AS `pv`
WHERE (pv.`feature_id` = 2 AND pv.`variant_id` = 2)
    AND (pv.`feature_id` = 3 AND pv.`variant_id` = 11)

您是否有任何其他想法如何接收产品:14,15由特定variant_id 6和11 http://prntscr.com/ect2oh

2 个答案:

答案 0 :(得分:0)

这是一种做你想做的事情的方法:

SELECT p.*, pd.name AS product_name
FROM product p LEFT JOIN
     product_description pd
     ON p.id = pd.product_id JOIN
     product_to_variant pv
     ON p.id = pv.product_id
WHERE p.status = 0 AND
      ((pv.feature_id = 2 AND pv.variant_id = 6) OR
       (pv.feature_id = 3 AND pv.variant_id = 11)
      )
GROUP BY p.id
HAVING COUNT(DISTINCT feature_id) = 2
ORDER BY p.id DESC;

注意:

  • 没有行可以满足您的原始条件。因为列不能同时具有两个值。因此OR而不是AND
  • HAVING子句检查两个值是否匹配。
  • 不需要LEFT JOINpv,因为您正在检查WHERE子句中该表的值 - 必须有匹配。
  • LEFT JOINpa可能也是不必要的。
  • 在任何地方使用反引号只会使查询更难写和阅读。

答案 1 :(得分:0)

也许是这样的:

SELECT pv.* FROM `product_to_variant` AS `pv`
WHERE (pv.`feature_id` = 2 AND pv.`variant_id` = 2)
OR (pv.`feature_id` = 3 AND pv.`variant_id` = 11)

而不是AND,而在结果中需要feature_idvariant_id,请使用OR,因为它需要两者。