【问题标题】:Select rows where a column has specific values with similar ID's选择列具有具有相似 ID 的特定值的行
【发布时间】:2021-07-29 21:53:57
【问题描述】:

我需要编写一个查询,我需要返回具有相似 ID 的行,并且它们需要包含特定值。在下面的示例中,有多个不同颜色的 ID。

我需要选择仅包含黄色、红色和蓝色的所有行。所以这里 0 和 2 的 ID 将返回这些行,而 1 和 3 将不会返回,因为它不包含我需要的特定集合。我还需要返回的 ID 和颜色。

ID Colors
0 Yellow
0 Red
0 Blue
1 Yellow
1 Red
2 Yellow
2 Red
2 Blue
3 Red
3 Green
3 Blue

返回的数据应该返回为

ID Colors
0 Yellow
0 Red
0 Blue
2 Yellow
2 Red
2 Blue

我在这里尝试过这样做,但我假设它不会工作,因为它选择了包含任何颜色的行。但它需要包含所有颜色。

SELECT `id` , `Colors` FROM Tbl WHERE COLORS IN ('Yellow','Red','Blue') GROUP BY `id` Order BY `ID`.

【问题讨论】:

标签: mysql


【解决方案1】:

下次请与数据共享架构,它可以节省其他愿意帮助您的人的时间。

Demo with Given Data

请注意,这只会确保所有必需的值 IN 子句存在。

SELECT id, colors 
FROM Test 
WHERE id IN (
       select id from Test 
       where  colors in ('Yellow','Red', 'Blue') 
       group by id having count(1) = 3
) 

样本数据:

create table Test(id integer, colors varchar(10));
                                          
insert into Test(id, colors) values 
(0, 'Yellow'), (0, 'Red'), (0, 'Blue'), 
(1, 'Yellow'),(1, 'Red'),
(2, 'Yellow'),(2, 'Red'), (2,'Blue'),
(3, 'Red'), (3, 'Green'), (3, 'Blue') ;


SELECT * FROM Test WHERE id IN (select id from Test where  colors in ('Yellow','Red', 'Blue') group by id having count(1) = 3) ;

测试结果:




mysql> create database test;
Query OK, 1 row affected (0.00 sec)

mysql> use test;
Database changed
mysql> create table Test(id integer, colors varchar(10));
Query OK, 0 rows affected (0.04 sec)

mysql> insert into Test(id, colors) values 
    -> (0, 'Yellow'), (0, 'Red'), (0, 'Blue'), 
    -> (1, 'Yellow'),(1, 'Red'),
    -> (2, 'Yellow'),(2, 'Red'), (2,'Blue'),
    -> (3, 'Red'), (3, 'Green'), (3, 'Blue') ;
Query OK, 11 rows affected (0.01 sec)
Records: 11  Duplicates: 0  Warnings: 0

mysql> select * from Test;
+------+--------+
| id   | colors |
+------+--------+
|    0 | Yellow |
|    0 | Red    |
|    0 | Blue   |
|    1 | Yellow |
|    1 | Red    |
|    2 | Yellow |
|    2 | Red    |
|    2 | Blue   |
|    3 | Red    |
|    3 | Green  |
|    3 | Blue   |
+------+--------+
11 rows in set (0.00 sec)

mysql> SELECT * FROM Test WHERE id IN (select id from Test where  colors in ('Yellow','Red', 'Blue') group by id having count(1) = 3) ;
+------+--------+
| id   | colors |
+------+--------+
|    0 | Yellow |
|    0 | Red    |
|    0 | Blue   |
|    2 | Yellow |
|    2 | Red    |
|    2 | Blue   |
+------+--------+
6 rows in set (0.00 sec)

mysql> -- For example for Green, Red, Blue
mysql> SELECT * FROM Test WHERE id IN (select id from Test where  colors in ('Green','Red', 'Blue') group by id having count(1) = 3) ;
+------+--------+
| id   | colors |
+------+--------+
|    3 | Red    |
|    3 | Green  |
|    3 | Blue   |
+------+--------+
3 rows in set (0.00 sec)


【讨论】:

  • 这对数据集做出了隐含的假设,虽然可能是正确的,但应该明确说明
  • @strawberry 你说得对,我同意,谢谢指正
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 2021-01-30
相关资源
最近更新 更多