mysql查询在基于product_id对行进行分组后运行查询

时间:2014-12-23 14:47:33

标签: mysql sql

我想编写一个mysql查询来获取不同的product_id,其中要显示类似product_id值的attribute_id列的组合。

我试过这个:

SELECT DISTINCT(product_id) FROM oc_product_attribute WHERE (attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1') and (attribute_id = 29 AND text = 'Flange')

   product_id  attribute_id    language_id     text
    1           12              1               0.25 - 20
    1           13              1               2500
    1           14              1               30
    1           15              1               130-160
    1           16              1               1.00
    1           17              1               0.50
    1           18              1               Medium accuracy
    1           19              1               PC mountable
    1           20              1               N/A
    2           21              1               50
    2           22              1               +/- +/-100
    2           23              1               +5
    2           24              1               2.5 v to +/-0.625
    2           25              1               DC to 20
    2           26              1               1.00
    2           27              1               < 1 % of FS
    2           28              1               4 PIN Connector
    2           29              1               Flange
    2           30              1               N/A

基本上我想要的是,查询应该在类似product_id列的不同行上运行,其中逻辑运算符具有连接和逻辑运算符。

如果问题不明确,请告诉我。

3 个答案:

答案 0 :(得分:0)

你需要做EXISTS()......

SELECT DISTINCT product_id
FROM oc_product_attribute t1 
WHERE EXISTS(SELECT * FROM oc_product_attribute t2 
  WHERE t1.product_id=t2.product_id
  AND attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1'
) 
AND EXISTS (SELECT * FROM oc_product_attribute t3
  WHERE t1.product_id=t3.product_id
AND attribute_id = 29 AND text = 'Flange')

如果您需要测试更多属性/文本组合,只需为每个组合添加另一个EXISTS()子句。

答案 1 :(得分:0)

您可以使用子查询和IN运算符来解决此问题。这样想吧。

首先,编写一个查询,提取符合第一个要求的所有product_id:

SELECT DISTINCT product_id
FROM oc_product_attribute
WHERE (attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1');

然后,编写第二个查询,提取与第一个要求匹配的所有product_id:

SELECT DISTINCT product_id
FROM oc_product_attribute
WHERE (attribute_id = 29 AND text = 'Flange');

现在,您可以编写最终查询,并希望从第一个结果集中选择其product_id值也在第二个集合的结果中的所有行。试试这个:

SELECT DISTINCT product_id
FROM oc_product_attribute
WHERE (attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1') AND product_id IN(
   SELECT DISTINCT product_id
   FROM oc_product_attribute
   WHERE (attribute_id = 29 AND text = 'Flange'));

答案 2 :(得分:-2)

你可以试试这个:

select distinct p_id from (SELECT DISTINCT(product_id) as p_id FROM oc_product_attribute WHERE (attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1') or (attribute_id = 29 AND text = 'Flange'))