MySQL,胶水表计数

时间:2012-07-19 07:54:25

标签: mysql

在胶合表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和& 6的产品数量。 1 = 1
选项ID为1 = 4的产品数量

我正在大脑冻结,无法弄明白 - 请帮忙......

4 个答案:

答案 0 :(得分:1)

select productid from product_options
where optionid in (6,7)
group by productid 
having count(distinct optionid)=2

答案 1 :(得分: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 DEMO here

答案 2 :(得分: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)

答案 3 :(得分:0)

试试这个

select productid  from product_options
where optionid in(6,7)
group  by productid 
having COUNT(*)=2