SQL 无需全部组合即可查找相似行
我有这个 SQL 表:
CREATE TABLE DATA (
ID NUMBER NOT NULL,
CODE VARCHAR(32) NOT NULL,
DESCRIPTION VARCHAR(256),
PRIMARY KEY (ID)
);
其中的一些值如下:
ID CODE DESC
1 'A' 'AAAA'
2 'B' 'BBB'
3 'A' 'AGAIN'
4 'C' 'CCC'
5 'A' 'ABBA'
我想检索具有相似代码的所有行,因为我需要在代码列上添加 UNIQUE 约束。
我有这个查询:
select distinct
t1.code, t1.id, t1.description, t2.id, t2.description
from
data t1, data t2
where
t1.code = t2.code and t1.id != t2.id
order by t1.code
这将返回我这个结果集:
A 5 ABBA 1 AAAA
A 3 AGAIN 1 AAAA
A 1 AAAA 5 ABBA
A 1 AAAA 3 AGAIN
A 3 AGAIN 5 ABBA
A 5 ABBA 3 AGAIN
如何调整查询以丢弃已列出的差异的组合? 在此示例中,我只想包含以下行:
A 1 AAAA 3 AGAIN
A 1 AAAA 5 ABBA
A 3 AGAIN 5 ABBA
I have this SQL table:
CREATE TABLE DATA (
ID NUMBER NOT NULL,
CODE VARCHAR(32) NOT NULL,
DESCRIPTION VARCHAR(256),
PRIMARY KEY (ID)
);
and some values in it like:
ID CODE DESC
1 'A' 'AAAA'
2 'B' 'BBB'
3 'A' 'AGAIN'
4 'C' 'CCC'
5 'A' 'ABBA'
I want to retrieve all lines with similar code because I need to add a UNIQUE constraint on the code column.
I have this query:
select distinct
t1.code, t1.id, t1.description, t2.id, t2.description
from
data t1, data t2
where
t1.code = t2.code and t1.id != t2.id
order by t1.code
That is returning me this result set:
A 5 ABBA 1 AAAA
A 3 AGAIN 1 AAAA
A 1 AAAA 5 ABBA
A 1 AAAA 3 AGAIN
A 3 AGAIN 5 ABBA
A 5 ABBA 3 AGAIN
How can I tweak the query to discard combination of already listed differences ?
In this example I want to have only this rows:
A 1 AAAA 3 AGAIN
A 1 AAAA 5 ABBA
A 3 AGAIN 5 ABBA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以只取每几行中的一行,例如:
you could take only one of each couple of rows, for instance: