检查表中是否存在特定元组

发布于 2024-12-13 18:04:07 字数 333 浏览 0 评论 0原文

有没有办法检查 where-in 语句中的表中是否存在特定元组?

类似于:

create table Test(A int, B int);

insert into Test values (3, 9);
insert into Test values (6, 7);
insert into Test values (7, 6);
insert into Test values (3, 4);

select A, B
from Test
where (B, A) in Test;

预期输出:

6|7
7|6

Is there a way to check if a specific tuple exists in a table in a where-in statement?

Something like:

create table Test(A int, B int);

insert into Test values (3, 9);
insert into Test values (6, 7);
insert into Test values (7, 6);
insert into Test values (3, 4);

select A, B
from Test
where (B, A) in Test;

Expected output:

6|7
7|6

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

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

发布评论

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

评论(3

泛滥成性 2024-12-20 18:04:07

你非常接近,“in”子句的后半部分必须是选择...所以

SELECT A,B
FROM Test
WHERE (B,A) IN (SELECT B,A FROM Test);

测试(IN)必须位于相同的字段(或字段类型)中

You were super close, the second half of an "in" clause has to be a select... so

SELECT A,B
FROM Test
WHERE (B,A) IN (SELECT B,A FROM Test);

The test (IN) must be in the same fields (or types of fields)

与风相奔跑 2024-12-20 18:04:07

因此将 Test 连接到自身:

select t1.A, t1.B
from Test t1
join Test t2 on t1.A = t2.B and t1.B = t2.A

或者使用交集:

select A, B from Test
intersect
select B, A from Test

不过,自连接可能会更快。

Join Test to itself thusly:

select t1.A, t1.B
from Test t1
join Test t2 on t1.A = t2.B and t1.B = t2.A

Or use an intersection:

select A, B from Test
intersect
select B, A from Test

The self-join would probably be faster though.

灰色世界里的红玫瑰 2024-12-20 18:04:07

当您在数据库上下文中以这种方式使用“元组”一词时,您可能会得到一些困惑,因为“元组”一词在数据库理论中也有一个正式的定义,该定义与您的问题中隐含的集合论定义不同。

如果您尝试识别不需要的元组,您可以尝试以下方法:

SELECT t1.A, t1.B From Test t1 JOIN Test t2 ON t1.A=t2.B AND t1.B=t2.A WHERE t1.A > t1.B

You may get some confused looks when you use the word "tuple" in that way in the context of a database, because the word "tuple" also has a formal definition in database theory that is different from the set theory definition implied in your question.

If you're trying to identify unwanted tuples, you could try this approach:

SELECT t1.A, t1.B From Test t1 JOIN Test t2 ON t1.A=t2.B AND t1.B=t2.A WHERE t1.A > t1.B
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文