[英]What is the best or simplest way to query the following
I need help with this problem.我需要帮助解决这个问题。
Question: Write an SQL query that lists all the species found in the oldest zoo in America.问题:编写一个 SQL 查询,列出在美国最古老的动物园中发现的所有物种。
I tried the following, which worked, but I would like to know if there is a simpler way to do this.我尝试了以下方法,它有效,但我想知道是否有更简单的方法可以做到这一点。 I spent hours on this question.我在这个问题上花了几个小时。
In the first block I created a new table I called "usaT", using the INTO clause, which only hold zoos with country USA.在第一个块中,我使用 INTO 子句创建了一个名为“usaT”的新表,该表仅包含美国国家/地区的动物园。 Click data base link to see image, please.请点击数据库链接查看图片。 Then i query this "usaT" table in the 2nd block of code.然后我在第二个代码块中查询这个“usaT”表。
Thanks for the help谢谢您的帮助
SELECT * INTO usaT
FROM zoos WHERE country='USA';
SELECT species FROM animals, usaT
WHERE year_founded = (SELECT MIN(year_founded) FROM usaT)
AND animals.zoo=usaT.city;
Don't use the ANSI (pre-ISO) style of SQL JOINs (ie FROM x, y WHERE x.fk = y.fk
).不要使用 SQL JOIN 的 ANSI(前 ISO)样式(即FROM x, y WHERE x.fk = y.fk
)。 Always use an explicit JOIN
.始终使用显式JOIN
。
Use SELECT DISTINCT
to prevent duplicate results where a zoo has more than 1 animal of the same species.使用SELECT DISTINCT
可防止动物园拥有超过 1 只相同物种的动物时出现重复结果。
You can get the oldest zoo by doing SELECT TOP 1... ORDER BY
(in MS SQL Server)您可以通过执行SELECT TOP 1... ORDER BY
获得最古老的动物园(在 MS SQL 服务器中)
LIMIT
.在 PostgreSQL (我认为您正在使用)中,您使用LIMIT
。Like so:像这样:
SELECT
DISTINCT
animals.species
FROM
animals
INNER JOIN
(
SELECT
TOP 1
city
FROM
zoos
WHERE
country = 'USA'
ORDER BY
year_founded ASC
) AS oldest_zoo_in_usa ON
animals.zoo = oldest_zoo_in_usa.city
SELECT
DISTINCT
animals.species
FROM
animals
INNER JOIN
(
SELECT
city
FROM
zoos
WHERE
country = 'USA'
ORDER BY
year_founded ASC
LIMIT
1
) AS oldest_zoo_in_usa ON
animals.zoo = oldest_zoo_in_usa.city
Query would be:查询将是:
Select s.*
from animals a join
zoos z on z.yearFounded=(Select min(year_founded) from zoos) and z.city=a.animals Join
Species s on a.species=s.species
You should assign the unique identification number to each row of the all table for simplicity and use that as primary key & foreign key relation for joins.为简单起见,您应该为 all 表的每一行分配唯一标识号,并将其用作连接的主键和外键关系。
select distinct species
from animals a
join zoos z
on z.year_founded in
(select min(year_founded)
from zoos
where country = 'USA')
and a.zoo = z.city;
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.