MySQL查询 - 1列上的多个WHERE子句

时间:2011-08-17 12:39:28

标签: mysql sql

任何人都可以根据下面的查询帮我构建一个查询。

正如您所看到的,我有一个产品规格和某些组在前端构建。我知道这个问题,1列不能同时是2个值,但我只需要那些2组中的那些产品。

为了说明,product_specification_sid,id 2 3和4是尺寸,de rest 8~11是颜色,所以我想选择一个有2和3的产品。

内部加入表格double不是一个选项,因为组(大小,颜色)将来可能会有所不同。

SELECT
    products.*,
    categories.*,
    manufacturers.* 
FROM products
INNER JOIN  product_categories ON product_category_pid = product_id
INNER JOIN  categories ON product_category_cid = category_id
INNER JOIN  manufacturers ON product_manufacturer = manufacturer_id
INNER JOIN  product_specifications ON product_specification_pid=product_id
WHERE 
    product_active = 1  
AND 
(
    product_specification_sid in (3)  
AND  
    product_specification_sid in (8,9,6,7,10,11)  
) 
GROUP BY product_id

2 个答案:

答案 0 :(得分:5)

您可以使用having子句。

SELECT
    products.*,
FROM products
INNER JOIN  product_categories ON product_category_pid = product_id
INNER JOIN  categories ON product_category_cid = category_id
INNER JOIN  manufacturers ON product_manufacturer = manufacturer_id
INNER JOIN  product_specifications ON product_specification_pid=product_id
WHERE product_active = 1  
GROUP BY product_id
HAVING COUNT(CASE WHEN product_specification_sid in (3) THEN 1 END) > 0
 AND COUNT(CASE WHEN product_specification_sid in (8,9,6,7,10,11) THEN 1 END) > 0

答案 1 :(得分:1)

据我了解,您正在寻找具有两个符合特定条件的匹配product_specification记录的产品记录。对我而言,就像直截了当的解决方案一样:

SELECT products.*, categories.*, manufacturers.*  
FROM products
INNER JOIN  product_categories ON product_category_pid = product_id
INNER JOIN  categories ON product_category_cid = category_id
INNER JOIN  manufacturers ON product_manufacturer = manufacturer_id
INNER JOIN  product_specifications ps1 ON ps1.product_specification_pid=product_id
INNER JOIN  product_specifications ps2 ON ps2.product_specification_pid=product_id
WHERE      product_active = 1
  AND  ps1.product_specification_sid in (3)
  AND  ps2.product_specification_sid in (8,9,6,7,10,11)

顺便说一下,“group by”不起作用。您必须按非聚合的所有内容进行分组,并且每个表必须至少有一列,因此您至少有三个非聚合。 (好吧,也许MySQL在这里有一些扩展,但是在标准的SQL中可以获得。)