如果我有两个这样的数据库表:
+-----------------+
| dog |
+-----------------+
| id |
| name |
| size |
+-----------------+
+-----------------+
| dog_color |
+-----------------+
| id |
| dog_id |
| color |
+-----------------+
我如何编写一个查询,以便结果返回所有具有黑色和白色的狗?狗也可以有其他颜色,但需要有黑色和白色。
答案 0 :(得分:2)
select dog.*, count(dog_color.color) as num_colors from dog
inner join dog_color on dog_color.dog_id = dog.id
where color in ('black', 'white')
group by dog.id
HAVING COUNT(DISTINCT dog_color.color) = 2;
应该这样做。
样本数据和测试:
mysql> select * from dog;
+------+-------+------+
| id | name | size |
+------+-------+------+
| 1 | fido | 0 |
| 2 | ruff | 0 |
| 3 | rover | 0 |
+------+-------+------+
3 rows in set (0.00 sec)
mysql> select * from dog_color;
+------+--------+-------+
| id | dog_id | color |
+------+--------+-------+
| 1 | 1 | black |
| 2 | 1 | white |
| 3 | 1 | brown |
| 4 | 2 | black |
| 5 | 3 | white |
+------+--------+-------+
5 rows in set (0.00 sec)
mysql> select dog.*, count(dog_color.color) as num_colors from dog
-> inner join dog_color on dog_color.dog_id = dog.id
-> where color in ('black', 'white')
-> group by dog.id
-> having num_colors = 2;
+------+------+------+------------+
| id | name | size | num_colors |
+------+------+------+------------+
| 1 | fido | 0 | 2 |
+------+------+------+------------+
1 row in set (0.00 sec)
答案 1 :(得分:2)
使用MySQL 5.1.x在下面测试的解决方案,返回至少具有白色和黑色颜色的所有狗:
SELECT dog.*,
group_concat(dc_all.color) AS colors
FROM dog
JOIN dog_color as dc_white on (dog.id = dc_white.dog_id AND dc_white.color = 'white')
JOIN dog_color as dc_black on (dog.id = dc_black.dog_id AND dc_black.color = 'black')
LEFT JOIN dog_color as dc_all on (dog.id = dc_all.dog_id);
答案 2 :(得分:1)
select distinct
d.id
, d.name
, d.size
from
dog d
inner join dog_color c1
on d.id = c1.dog_id
and c1.color in ('white')
inner join dog_color c2
on d.id = c2.dog_id
and c2.color in ('black')