1

在粘合表 product_options 中,我有以下字段... id、productid、optionid

CREATE TABLE `product_options` (
`id`  int NULL AUTO_INCREMENT ,
`productid`  int NULL ,
`optionid`  int NULL ,
PRIMARY KEY (`id`)
)
;

INSERT INTO product_options 
(productid, optionid)
VALUES 
(1,2),(1,4),(1,5),(1,6),(1,7),(2,4),(2,3),(2,1),(2,7),(3,1),(3,4),(4,1),(4,7),(4,6),(5,1)

(见http://www.sqlfiddle.com/#!2/3d309

现在,我想计算不同选项组合的产品数量。

例如,我追求的结果是...
选项 ID 为 6 和 7
的产品数量 = 2 所有选项 ID 为 6、7 和 1
的产品数量 = 1 选项 ID 为 1 的产品数量 = 4

我的大脑冻结了,无法弄清楚-请帮助...

4

4 回答 4

1
select productid from product_options
where optionid in (6,7)
group by productid 
having count(distinct optionid)=2
于 2012-07-19T07:59:33.853 回答
1

请尝试以下:

select count(*) as count0,opt from
(select productid,group_concat(optionid)as opt from product_options
where optionid in (1)
group by productid 
having count(distinct optionid)=1) a    
UNION    
select count(*) as count0,opt from
(select productid,group_concat(optionid)as opt from product_options
where optionid in (6,7)
group by productid 
having count(distinct optionid)=2) b    
UNION    
select count(*) as count0,opt from
(select productid,group_concat(optionid)as opt from product_options
where optionid in (1,6,7)
group by productid 
having count(distinct optionid)=3) c

SQL 演示在这里

于 2012-07-19T08:58:20.717 回答
0

尝试这个

select productid  from product_options
where optionid in(6,7)
group  by productid 
having COUNT(*)=2
于 2012-07-19T08:01:11.077 回答
0

你的意思是这样的吗?

SELECT * 
FROM product_options 
WHERE optionid IN (6, 7) 
GROUP BY productid

或者如果你只是想COUNT试试

SELECT COUNT(DISTINCT(productid)) 
FROM product_options 
WHERE optionid IN (6, 7)
于 2012-07-19T07:58:19.733 回答