什么是查询以下内容的最佳或最简单方法

问题描述 投票:0回答:3

我需要有关此问题的帮助。

问题:编写一个SQL查询,列出在美国最古老的动物园中发现的所有物种。

我尝试了以下方法,但确实有效,但是我想知道是否有更简单的方法来执行此操作。我花了几个小时解决这个问题。

[在第一块中,我使用INTO子句创建了一个名为“ usaT”的新表,该表仅容纳美国国家/地区的动物园。单击数据库链接以查看图像。然后,我在第二个代码块中查询此“ usaT”表。

感谢您的帮助

database photo

    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;
sql database pgadmin
3个回答
1
投票
  • 请勿使用SQL JOIN的ANSI(ISO前)样式(即FROM x, y WHERE x.fk = y.fk)。始终使用明确的JOIN

  • 使用SELECT DISTINCT来防止重复结果,而动物园中有1个以上相同物种的动物。

  • 您可以通过执行SELECT TOP 1 ... ORDER BY(在MS SQL Server中获得最早的动物园)

    • 在PostgreSQL(我认为您正在使用的PostgreSQL中,您使用LIMIT

例如:

MS SQL Server

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

PostgreSQL

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

0
投票

查询将是:

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

为简单起见,您应该为所有表的每一行分配唯一的标识号,并将其用作连接的主键和外键关系。


0
投票
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;

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.