2016-07-24 65 views
0

我有一张包含许多不同产品规格记录的表,因为它们有不同的颜色,产品在表中可能会出现多次。为了在屏幕上显示产品,我需要用黄色来选择它们的列表,但是如果黄色不存在,我需要蓝色,否则我不想要这个产品。在MySQL的所有记录组中选择一组记录中的特定记录

简化产品例如:

 
+----+--------+ 
| ID | NAME | 
+----+--------+ 
| 1 | Prod A | 
| 2 | Prod B | 
| 3 | Prod C | 
| 4 | Prod D | 
+----+--------+ 

简单求参数表:

 
+----+------------+--------+ 
| ID | ID_PRODUCT | COLOR | 
+----+------------+--------+ 
| 1 |   1 | BLUE | 
| 2 |   1 | YELLOW | 
| 3 |   2 | RED | 
| 4 |   2 | PINK | 
| 5 |   3 | BLUE | 
| 6 |   3 | GRAY | 
| 7 |   4 | YELLOW | 
+----+------------+--------+ 

预期结果:

 
+----+------------+--------+ 
| ID | ID_PRODUCT | COLOR | 
+----+------------+--------+ 
| 2 |   1 | YELLOW | 
| 5 |   3 | BLUE | 
| 7 |   4 | YELLOW | 
+----+------------+--------+ 

原始SQL这个例子:

 
CREATE TABLE `colors` (
    `ID` int(11) NOT NULL, 
    `ID_PRODUCT` int(11) DEFAULT NULL, 
    `COLOR` varchar(16) DEFAULT NULL, 
    PRIMARY KEY (`ID`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

CREATE TABLE `products` (
    `ID` int(11) NOT NULL, 
    `NAME` varchar(16) DEFAULT NULL, 
    PRIMARY KEY (`ID`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

INSERT INTO `colors` VALUES (1,1,'BLUE'),(2,1,'YELLOW'),(3,2,'RED'),(4,2,'PINK'),(5,3,'BLUE'),(6,3,'GRAY'),(7,4,'YELLOW'); 

INSERT INTO `products` VALUES (1,'Prod A'),(2,'Prod B'),(3,'Prod C'),(4,'Prod D'); 

回答

0

下面是使用conditional aggregation一个选项:

select id_product, 
     max(case when color = 'YELLOW' then id 
       when color = 'BLUE' then id 
      end), 
     max(case when color = 'YELLOW' then color 
       when color = 'BLUE' then color 
      end) 
from colors 
where color in ('YELLOW','BLUE') 
group by id_product 
+0

我的英语理解能力不好,让我不能正确理解你对我接受答案的关注。事实上,在Darshan Mehta的回答中,身份证并不总是正确的。你的回答更加复杂但正确。 –

0

这里有一个方法:

select c.* 
from colors c 
where c.color = 'YELLOW' 
union all 
select c.* 
from colors c 
where c.color = 'BLUE' and 
     not exists (select 1 
        from colors c2 
        where c2.id_product = c.id_product and c2.color = 'YELLOW' 
       ); 
+0

也非常感谢,但由于联合和子选择,它似乎过于复杂。 –

+0

@AndréDias。 。 。使用正确的索引,这可能是获得所需结果的最快方法。 –

+0

嗨,请告诉我什么索引(如果可能,以业余方式)我需要添加,以便我可以比较两种解决方案。我有超过80000条记录。 –

0

如果它总是将是蓝色和黄色比较那么我d只需使用max()函数,例如

select id, id_product, max(color) from colors 
where color in ('BLUE','YELLOW') 
group by id_product; 
+0

虽然这将返回正确的颜色,但它会为'id'字段返回任意值。 'mysql'允许这种行为,大多数其他数据库不会... – sgeddes

+0

因为在这个主题中,mysql是唯一的数据库,我接受这个解决方案,因为它是所有选项中最简单的。 –

+0

我现在明白你的意思是“id为任意值”,这个解决方案不能按预期工作。 –