为MySQL中的所有记录组选择一组记录中的特定记录

时间:2016-07-24 23:04:28

标签: php mysql sql

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

简化产品示例:

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

Simplied Spec table:

+----+------------+--------+
| 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');

3 个答案:

答案 0 :(得分: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'
                 );

答案 1 :(得分: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

答案 2 :(得分:0)

如果总是进行蓝色和黄色比较,那么我只使用max()函数,例如

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