下次请与数据共享架构,它可以节省其他愿意帮助您的人的时间。
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)