Nesting queries in SQL

前端 未结 4 834
余生分开走
余生分开走 2020-12-28 20:11

The goal of my query is to return the country name and its head of state if it\'s headofstate has a name starting with A, and the capital of the country has greater than 100

相关标签:
4条回答
  • 2020-12-28 20:39

    You need to join the two tables and then filter the result in where clause:

    SELECT country.name as country, country.headofstate 
    from country
    inner join city on city.id = country.capital
    where city.population > 100000
    and country.headofstate like 'A%'
    
    0 讨论(0)
  • 2020-12-28 20:45

    If it has to be "nested", this would be one way, to get your job done:

    SELECT o.name AS country, o.headofstate 
    FROM   country o
    WHERE  o.headofstate like 'A%'
    AND   (
        SELECT i.population
        FROM   city i
        WHERE  i.id = o.capital
        ) > 100000
    

    A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

    0 讨论(0)
  • 2020-12-28 20:45

    Query below should help you achieve what you want.

    select scountry, headofstate from data 
    where data.scountry like 'a%'and ttlppl>=100000
    
    0 讨论(0)
  • 2020-12-28 20:54

    The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

    SELECT country.name, country.headofstate
    FROM country 
    WHERE country.headofstate LIKE 'A%' AND 
    country.id in (SELECT country_id FROM city WHERE population > 100000)
    

    Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

    0 讨论(0)
提交回复
热议问题