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を参照)

ここで、オプションのさまざまな組み合わせの製品数を取得したいと思います。

たとえば、私が求めている結果は次のとおりです...
オプションID6と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 * 
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 に答える
0

これを試して

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