在SQL中,我们可以使用“Union”来表示。合并两个表。 “交叉”有哪些不同的方法?

发布于 2024-08-30 12:02:22 字数 417 浏览 1 评论 0原文

在 SQL 中,有一个运算符可以“联合”两个表。在一次采访中,有人告诉我,假设一个表只有 1 个字段,其中有 1、2、7、8,而另一个表也只有 1 个字段,其中有 2、7,我如何获得交集。一开始我很震惊,因为我从来没有这样看过。

后来我发现它实际上是一个“Join”(内连接),这只是

select * from t1, t2 where t1.number = t2.number

(虽然“join”这个名字感觉更像是“union”而不是“intersect”)

另一种解决方案似乎是

select * from t1 INTERSECT select * from t2

但不支持在 MySQL 中。除了这两种方法之外,还有其他方法可以获取交集吗?

In SQL, there is an operator to "Union" two tables. In an interview, I was told that, say one table has just 1 field with 1, 2, 7, 8 in it, and another table also has just 1 field with 2, and 7 in it, how do I get the intersection. I was stunned at first, because I never saw it that way.

Later on, I found that it is actually a "Join" (inner join), which is just

select * from t1, t2 where t1.number = t2.number

(although the name "join" feels more like "union" rather than "intersect")

another solution seems to be

select * from t1 INTERSECT select * from t2

but it is not supported in MySQL. Are there different ways to get the intersection besides these two methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞慾 2024-09-06 12:02:22

这个页面解释了如何在MySQL中实现INTERSECT和MINUS。要实现 INTERSECT,您应该使用内部联接:

SELECT t1.number
FROM t1
INNER JOIN t2
ON t1.number = t2.number

您的代码也执行此操作,但不建议再编写这样的联接。

This page explains how to implement INTERSECT and MINUS in MySQL. To implement INTERSECT you should use an inner join:

SELECT t1.number
FROM t1
INNER JOIN t2
ON t1.number = t2.number

Your code does this too, but it is not recommended to write joins like that any more.

谷夏 2024-09-06 12:02:22

相交只是一个内连接。所以

select * from t1 INTERSECT select * from t2

可以像MySQL一样重写

select * 
from t1 
inner join t2
on t1.col1 = t2.col1
and t1.col2 = t2.col2
and t1.col3 = t2.col3
...

An intersect is just an inner join. So

select * from t1 INTERSECT select * from t2

can be rewritten for MySQL like

select * 
from t1 
inner join t2
on t1.col1 = t2.col1
and t1.col2 = t2.col2
and t1.col3 = t2.col3
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文