2016-12-08 58 views
1

我一直在使用这一段时间,我无法找到灵魂,所以也许你可以帮助我。遇到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

回答

3

你的子查询搜索整个表为你感兴趣的,不仅仅是产品相同行的代码。

如果您希望仅针对具有相同产品的行对子查询进行评估,则需要使用相关子查询

select p.product, 
    case 
    when exists(select 1 from table1 where code=1 and product=p.product) = 1 
     and exists(select 1 from table1 where code=2 and product=p.product) = 1 
    then 'Types are : 1,2' 
    when exists(select 1 from table1 where code=1 and product=p.product) = 1 
     and exists(select 1 from table1 where code=2 and product=p.product) = 0 
    then 'Type is : 1' 
    when exists(select 1 from table1 where code=1 and product=p.product) = 0 
     and exists(select 1 from table1 where code=2 and product=p.product) = 1 
    then 'Type is : 2' 
    else 
     'There are no types 1 or 2' 
    end as response 
from table1 as p 
group by product 

输出:

+----------+------------------+ 
| product | response   | 
+----------+------------------+ 
| product1 | Types are : 1,2 | 
| product2 | Type is : 2  | 
| product3 | Type is : 1  | 
+----------+------------------+ 

不过,我通常会避免相关子查询,因为它们是性能如此昂贵。 MySQL必须为外部查询中的每一行重新执行子查询。

下面是一个使用子查询没有给出,但同样结果的替代查询:

SELECT product, 
    CASE GROUP_CONCAT(CASE WHEN code IN (1,2) THEN code ELSE NULL END ORDER BY code) 
    WHEN '1' THEN 'Type is : 1' 
    WHEN '1,2' THEN 'Types are: 1,2' 
    WHEN '2' THEN 'Type is : 2' 
    ELSE 'There are no types 1 or 2' 
    END AS response 
FROM table1 
GROUP BY product 
+1

肯定的方式更快,我很担心性能,但现在不是了。 – None