我一直在使用这一段时间,我无法找到灵魂,所以也许你可以帮助我。遇到EXISTS和GROUP BY的问题
我有一张有3列'id''产品'代码的表格,产品可以重复使用,但每个产品的代码必须是唯一的。这是表的结构:
CREATE TABLE table1
(`id` int, `product` varchar(10), `code` int)
;
INSERT INTO table1
(`id`, `product`, `code`)
VALUES
(1, 'product1', 1),
(2, 'product1', 2),
(3, 'product1', 3),
(4, 'product2', 2),
(5, 'product2', 3),
(6, 'product3', 1),
(7, 'product3', 3)
;
那么我现在要做的是案件清单,如果一个产品有码1和码2,在响应列,显示出一定的价值,如果产品只有代码1显示另一个值,如果产品具有代码2,则其他值,如果产品既没有代码1也没有代码2,则显示另一个值(代码3在本例中不相关)。
这是我走这么远
select product,
case
when exists(select 1 from table1 where code=1) = 1
and exists(select 1 from table1 where code=2) = 1
then 'Types are : 1,2'
when exists(select 1 from table1 where code=1) = 1
and exists(select 1 from table1 where code=2) = 0
then 'Type is : 1'
when exists(select 1 from table1 where code=1) = 0
and exists(select 1 from table1 where code=2) = 1
then 'Type is : 2'
else
'There are no types 1 or 2'
end as response
from table1
group by product
的问题是,结果集只显示“类型有:1,2”在产品1,产品2和产品3我的回答专栏中,我相信,在子选择正在搜索所有产品(而不是每个产品),因此总是存在代码1和代码2。
任何你可以提供的帮助或方向将是非常受欢迎的。
感谢您的阅读。
小提琴例如:http://sqlfiddle.com/#!9/25eb55/3
肯定的方式更快,我很担心性能,但现在不是了。 – None