简体   繁体   English

SQL初学者:子查询

[英]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.问题是列出居住在apt 203的租户的姓名和DOB。上面的查询是正确的。 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.在您的情况下,最好使用 join 代替。

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 .接下来,您定义过滤谓词,即apt_no = 203 Finally, you choose which attributes you want to return ( t.tenant_name, t.tenant_dob ).最后,您选择要返回的属性 ( 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.当您的过滤(where 子句)很复杂时,子查询很有用,并且使用连接来表达它会弄乱您的代码。 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.您想根据表 B 中的某个谓词从表 A 中选择一行。您需要 A 和 B 之间的链接。在您的子查询中,您选择了表 B 中的键以在表 A 中找到合适的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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