gpt4 book ai didi

mysql - SQL : How to join tables right?

转载 作者:行者123 更新时间:2023-11-28 23:28:38 24 4
gpt4 key购买 nike

假设我有 3 个表:

CREATE TABLE animals 
(
animal_id INT PRIMARY KEY,
animal_name VARCHAR(100)
);

CREATE TABLE zoos
(
zoo_id INT PRIMARY KEY,
zoo_name VARCHAR(100)
);

CREATE TABLE zoo_has_animals
(
zoo_id INT,
animal_id INT
);

我需要得到所有空的动物园。我尝试使用下一个脚本加入他们:

SELECT zoos.zoo_name
FROM zoos
LEFT JOIN zoo_has_animals ON zoos.zoo_id = zoo_has_animals.zoo_id;

但它返回所有非空动物园而不是所需的空动物园。我做错了什么?

最佳答案

根本不需要JOIN:

SELECT z.zoo_name
FROM zoos as z
WHERE NOT EXISTS(SELECT 1 FROM zoo_has_animals
WHERE zoo_id = z.zoo_id);

使用JOIN:

SELECT z.zoo_name
FROM zoos as z
LEFT JOIN zoo_has_animals as h
ON z.zoo_id = h.zoo_id
WHERE h.zoo_id IS NULL;

关于mysql - SQL : How to join tables right?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38207761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com