Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting queries in SQL

Tags:

sql

nested

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,000 people utilizing a nested query.

Here is my query:

SELECT country.name as country, 
       (SELECT country.headofstate 
        from country 
        where country.headofstate like 'A%')      
from country, city 
where city.population > 100000;

I've tried reversing it, placing it in the where clause etc. I don't get nested queries. I'm just getting errors back, like "subquery returns more than one row" and such. If someone could help me out with how to order it, and explain why it needs to be a certain way, that'd be great.

like image 469
ZAX Avatar asked Sep 17 '12 21:09

ZAX


2 Answers

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?

like image 137
Erwin Brandstetter Avatar answered Oct 12 '22 12:10

Erwin Brandstetter


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%'
like image 41
Adriano Carneiro Avatar answered Oct 12 '22 13:10

Adriano Carneiro