同一张表上的联合

发布于 2024-09-03 15:40:50 字数 325 浏览 8 评论 0原文

我有一个表:

ID | Id1 | Id2
1  | 100 | 12
2  | 196 | 140
3  | 196 | 141
4  | 150 | 140
5  | 150 | 199

我想编写一个查询,该查询将为我提供一个包含具有相同 ID2 且 id1 等于 196 或 150 的记录的表。 我想到了 union:

select * from table where ID1 = 196 联盟 select * from table where ID1 = 150

但这不满足 ID2 要求。 我该怎么做呢?

I have a table:

ID | Id1 | Id2
1  | 100 | 12
2  | 196 | 140
3  | 196 | 141
4  | 150 | 140
5  | 150 | 199

I want to write a query that will give me a table containing records with the same ID2 and with id1 equal to 196 or 150.
I thought about union:

select * from table where ID1 = 196
union
select * from table where ID1 = 150

but that doesn't cover the ID2 requirement.
How should I do that?

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

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

发布评论

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

评论(4

南汐寒笙箫 2024-09-10 15:40:50

如果我正确理解你的问题那么这应该是答案:

select * from mytable where id2 in
(select id2 from mytable
group by id2
having count(*)>=2)
and (id1=196 or id1=150)

If I understood your question correctly then this should be the answer:

select * from mytable where id2 in
(select id2 from mytable
group by id2
having count(*)>=2)
and (id1=196 or id1=150)
九公里浅绿 2024-09-10 15:40:50

为什么要建立工会

您可以使用 in 完成相同的任务。

SELECT * FROM Table WHERE Id1 IN (196, 150) OR Id2 IN (196, 150)

Why are you doing a union?

You could accomplish the same task with in.

SELECT * FROM Table WHERE Id1 IN (196, 150) OR Id2 IN (196, 150)
月竹挽风 2024-09-10 15:40:50
SELECT ID
FROm yourTable as table1
INNER JOIN yourTable as table2
ON table1.Id2 = table2.Id2
WHERE table1.id1 IN (196.150)

开始了

SELECT ID
FROm yourTable as table1
INNER JOIN yourTable as table2
ON table1.Id2 = table2.Id2
WHERE table1.id1 IN (196.150)

here we go

撩人痒 2024-09-10 15:40:50

您可以将表连接到自身,

 select T1.* from Mytable T1 inner join MyTable T2 
 ON T1.ID2 = T2.ID2
 AND T1.ID1 in (196, 150)

类似这样,根据您的具体要求和表结构,您可能需要做更多的工作以避免重复条目。

You can join the table to itself

 select T1.* from Mytable T1 inner join MyTable T2 
 ON T1.ID2 = T2.ID2
 AND T1.ID1 in (196, 150)

Something like that, depending on your exact requirement and table structures you may need to do a little more work to avoid duplicate entries.

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