简体   繁体   中英

SQL beginner : sub-query

select tenant_name, tenant_dob
from tenant
where rental_no = (select rental_no
                    from rental
                    where apt_no = 203);

The question is that listing the name and DOB of tenants who live in apt 203. The query on the above is correct one. My coding is below. I know that I did not use sub-query statement. Actually, I can just simply memorize statement of sub-query for school exam questions, but I would like to know when do I have to use the sub-query, and why I have to use the sub-query. Also, please tell me things that I have to know about sub-query to use it.

select tenant_name, tenant_dob
from tenant
where rental_no = 203;

In your case, it's much better to use join instead.

select t.tenant_name, t.tenant_dob
from tenant t join rental r on t.rental_no = r.rental_no
where t.rental_no = apt_no = 203;

You join tenant and rental, so they are perceived as one by the database. Next, you define your filter predicate, which is apt_no = 203 . Finally, you choose which attributes you want to return ( t.tenant_name, t.tenant_dob ).

That's conceptually proper way of solving this task in a relational database.

Subqueries are useful when your filtering (the where clause) is complex, and expressing it using joins would mess up your code. In that case, it can simplify your query a lot but in your case, it does the opposite.

why I have to use the sub-query? You want to select a row from table A based on some predicate in table B. You need a link between A and B. In you subquery you selected key in table B to find a proper row in table A.

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