如何使用多个 And 条件,其中我使用内部联接组合了三个表
Posted
技术标签:
【中文标题】如何使用多个 And 条件,其中我使用内部联接组合了三个表【英文标题】:how to use multiple And condition where I combined three tables using inner join 【发布时间】:2022-01-14 20:59:55 【问题描述】: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";
【问题讨论】:
这不行吗? 它正在创建一个空值的表 【参考方案1】:您的问题与联接无关,您有三个相互矛盾的 AND 条件。 只需将其替换为 OR 即可使用
【讨论】:
但我必须显示一个查询:- 显示所有拥有大象、老虎和豹子的动物园的列表。 想想你想要的列表中的每一种动物——它不是大象、老虎和豹子——它要么是大象、老虎要么是豹子 有道理。如果这三种动物都属于同一个动物园,那么它会显示表格【参考方案2】:我觉得你需要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 | animal_type | animal_gender | animal_name |
---|---|---|---|
The Wild Zoo | Elephant | Male | adam |
The Wild Zoo | Leopard | Male | allen |
The Wild Zoo | Tiger | Female | nancy |
The Wild Zoo | Tiger | Male | tommy |
zoo_id | zoo_name | Tigers | Elephants | Leopards | FemaleTigers | FemaleElephants | FemaleLeopards | AnimalTypes |
---|---|---|---|---|---|---|---|---|
1 | The Wild Zoo | 2 | 1 | 1 | 1 | 0 | 0 | 4 |
dbfiddle here
上的演示【讨论】:
感谢它现在将每只动物的计数值显示为值 1 在我的表动物中,在类型列中我已经提到了老虎两次,所以它应该输出的计数为 2 代表老虎,1 代表大象,1 代表豹。我说的对吗? 我要写的查询是显示所有拥有大象、老虎和豹子的动物园的列表。 如果没有样本数据,我不确定您的期望。计数将基于分组的内容。 id name type 性别祖先_id no 1 tommy Tiger Male 1 5 2 cany Lion Male 2 5 3 adam Elephant Male 3 5 4 nancy Tiger Female 4 5 5 allen Leopard Male 5 5以上是关于如何使用多个 And 条件,其中我使用内部联接组合了三个表的主要内容,如果未能解决你的问题,请参考以下文章