如何使用多个AND条件,其中我使用内部连接组合了三个表
SELECT z.name, a.name, a.type, a.gender,
(
SELECT
COUNT(a.type)
FROM animal a
)
FROM zoo z
INNER JOIN zoo_animal_map m
ON z.id = m.zoo_id
INNER JOIN animal a
ON a.id = m.animal_id
WHERE a.type="Tiger" AND a.type ="Elephant" AND a.type =" Leopard";
解决方案
我认为您需要IN
SELECT
zoo.name AS zoo_name
, ani.type AS animal_type
, ani.gender AS animal_gender
, ani.name AS animal_name
FROM zoo_animal_map AS map
JOIN zoo AS zoo
ON zoo.id = map.zoo_id
JOIN animal AS ani
ON ani.id = map.animal_id
WHERE ani.type IN ('Tiger', 'Elephant', 'Leopard')
ORDER BY zoo.name, ani.type, ani.gender, ani.name
没有既是老虎又是大象的动物。
不过,我不太确定是不是有豹子。
但是如果您想要查找所有3种类型的动物园呢?
然后按动物园分组,使用条件聚合可能适合您。
SELECT *
FROM
(
SELECT
map.zoo_id
, zoo.name AS zoo_name
, COUNT(CASE
WHEN ani.type = 'Tiger'
THEN ani.id
END) AS Tigers
, COUNT(CASE
WHEN ani.type = 'Elephant'
THEN ani.id
END) AS Elephants
, COUNT(CASE
WHEN ani.type = 'Leopard'
THEN ani.id
END) AS Leopards
, COUNT(CASE
WHEN ani.type = 'Tiger'
AND ani.gender LIKE 'F%'
THEN ani.id
END) AS FemaleTigers
, COUNT(CASE
WHEN ani.type = 'Elephant'
AND ani.gender LIKE 'F%'
THEN ani.id
END) AS FemaleElephants
, COUNT(CASE
WHEN ani.type = 'Leopard'
AND ani.gender LIKE 'F%'
THEN ani.id
END) AS FemaleLeopards
, COUNT(DISTINCT ani.type) AS AnimalTypes
FROM zoo_animal_map AS map
JOIN zoo AS zoo
ON zoo.id = map.zoo_id
JOIN animal AS ani
ON ani.id = map.animal_id
GROUP BY map.zoo_id, zoo.name
) AS zoos
WHERE Tigers > 0
AND Elephants > 0
AND Leopards > 0
ORDER BY zoo_name
zoo_name | MOVICAL_TYPE | 动物性别 | 动物名称 |
---|---|---|---|
野生动物园 | 大象 | 凸形 | ADAM |
野生动物园 | 豹纹 | 凸形 | Allen |
野生动物园 | TIGER | 女性 | 南希 |
野生动物园 | TIGER | 凸形 | Tommy |
zoo_id | zoo_name | 老虎 | 大象 | 豹子 | FemaleTigers | 雌象 | FemaleLeopards | AnimalTypes |
---|---|---|---|---|---|---|---|---|
1 | 野生动物园 | 2 | 1 | 1 | 1 | 0 | 0 | 4 |
db<;>;小提琴演示here
相关文章