【发布时间】:2016-12-08 17:47:26
【问题描述】:
我一直在处理这个问题,我找不到灵魂,所以也许你可以帮助我。
我有一个包含 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和产品3的响应列中显示“类型是:1,2”,我相信在子选择中搜索所有产品(而不是每个产品)所以总是确实存在代码 1 和代码 2。
我们非常欢迎您提供任何帮助或指导。
感谢阅读。
【问题讨论】: