简体   繁体   中英

SQL nested select statement query

I want to get a Per capita income of a city (From table 1) which has a school that has a safety_score 1.

1.

select capitaincome, t1.city, safety_score
from tab1 t1,
     tab1 t2
where t1.city in (select t2.city from tab2 where safety_score = 1)   

2.

select capitaincome, t1.city, safety_score 
from tab1 t1,
     tab1 t2
where t1.city in (select city from tab2 where safety_score = 1)

These two give me different outputs just cause of one change in the nested select statement (t2.city and city). Both of them do not give the required output of one school but instead the first gives a list of all cities and their schools safety scores and the second gives me a list of the city with the least safety score but also all other schools in that city. Is this error because both tables have the column name city or is there a mistake in the logic and understanding?

It would be much easier if you could provide the complete structure of your tables. I guess your table structure is something like:

tab1 has column capitaincome and city

tab2 has column safety_score and city

The error is not because both tables have the same column name, that is fine. There is a problem in the logic and understanding.

The problem is, that you are creating a cartesian product but you want an inner join: While Cartesian Product provides you a result made by joining each row from one table with each row in another table an inner join gives you aa result where each row from one table with the same attribute value (in your case same city) pairs a row from the other table with the same attribute value.

You cannot solve this problem using a subquery and a cartesian product.

What you need to do is using a join clause:

select t1.capitaincome, t1.city, t2.safety_score
  from tab1 t1
  join tab2 t2 on t1.city = t2.city
 where t2.safety_score = 1

Or you can solve the problem using the old style join:

select t1.capitaincome, t1.city, t2.safety_score
  from tab1 t1,
       tab2 t2 
 where t1.city = t2.city
   and t2.safety_score = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM