在SQL中,如果我们只想求交集,是不是可以一直写一个内连接语句作为主查询和子查询呢?
在SQL中,如果我们只想找到交集,我们是否可以总是编写一个内连接语句作为主查询和子查询,反之亦然?
例如,
select * from gifts g where g.giftID in (select giftID from sentGifts);
可以进行连接并显示在sentGifts 表中发送的礼物,但它无法显示sentTime,因为它位于子查询内。但如果我们只关心找到交集,而不关心显示的内容,那么我们总能将一个转换为另一个吗?
In SQL, can we always write an inner join statement as a main query and subquery or vice versa if we only want to find the intersection?
For example,
select * from gifts g where g.giftID in (select giftID from sentGifts);
can do a join and show the gifts sent in the sentGifts table, but it won't be able to show the sentTime because that is inside the subquery. But if all we care is to find the intersection, without caring what is being displayed, then we can always convert one to the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以,只有在加入单个列时才可以这样做。当表通过多部分键连接时它将不起作用。
例如:
如果两个表上唯一的唯一标识符是(Number,Name)的组合,那么就没有办法将上面的语句转换为子查询类型的语句。
No, you can only do that if you are joining on a single column. It won't work when tables are connected via multi-part keys.
For example:
If the only unique identifier on both tables is the combination of (Number, Name), then there's no way to convert the above into a subquery-type statement.
在集合术语中,两个查询都会找到两个集合的交集,因此使用哪种形式并不重要。
您始终能够将一种形式转换为另一种形式。
作为实际使用的问题 - 如果您使用基于集合的 JOIN 方法(它们针对连接进行了更好的优化),大多数 RDBMS 的性能会更好。正如您所提到的,还有返回结果集的问题 - 如果您需要两个集合中的数据,则必须使用联接。
In set terms, both queries will find the intersection of the two sets, so that does not matter which form you use.
You will always be able to convert one form to the other.
As a matter of practical use - most RDBMSs will perform better if you use a set based approach with JOINs (they are better optimized for joins). As you mentioned, there is also the matter of the returned result set - you have to use a join if you need data from both sets.