我试图绕过这个SQL查询,但我真的遇到了麻烦。
我有一个包含id
和address
的表格(其中id
只是一个小写的addresss
和"id-"
前缀。我想得到所有的此列表中ID与地址匹配的元素,但地址 由列表中的2个元素共享。
例如:
答:id="id-abcde"
,address=aBcDe
B:id="id-zxwy"
,address=aBcDe
我想返回B,它在表中共享一个地址,其地址与其id不同。
我现在的查询是
select a.id, a.address
from users as a
where a.id != concat('id-', lower(a.address))
group by a.address, a.id
having count(1) > 1
但是,这并没有返回正确的结果。
任何和所有帮助将不胜感激!
答案 0 :(得分:1)
我想你想要:
select u.id, u.address
from (select u.*, count(*) over (partition by address) as cnt
from users u
) u
where u.id <> concat('id-', lower(u.address)) and cnt = 2;
如果您想要至少两个元素,请使用cnt > 1
。
答案 1 :(得分:0)
I don't think you need group by or having for this
try
select a.id, a.address from users a
where a.id != concat('id-',lower(a.address))
if you have multiple similar entries add distinct
in the first line
select distinct a.id, a.address from users a
答案 2 :(得分:0)
尝试*不区分1,这样就可以测试多次出现的行而不只是一列。
select a.id, a.address from users as a where
a.id != concat('id-', lower(a.address))
group by a.address, a.id
having count(*) > 1