postgresql 查找所有链接行的sql查询

sycxhyv7  于 2023-01-12  发布在  PostgreSQL
关注(0)|答案(2)|浏览(131)

我有一个表"用户":

drop table users;
CREATE TABLE users(
id int,
user_id int,
phone_number VARCHAR(30),
email VARCHAR(30));
INSERT INTO users
VALUES
(1, 999, 61412308310, 'can@gmail.com '),
(2, 129, 61477708777, 'acdc@gmail.com '),
(3, 213, 61488908495, 'adel99@gmail.com'),
(4, 145, 61477708777, 'austr@gmail.com'),
(5, 214, 61421445777, 'austr@gmail.com'),
(6, 214, 61421445326, 'jango@gmail.com');

我想选择具有重复user_id、重复phone_number或重复email的所有行。
结果应为:

2, 129, 61477708777, 'acdc@gmail.com '
4, 145, 61477708777, 'austr@gmail.com'
5, 214, 61421445777, 'austr@gmail.com'
6, 214, 61421445326, 'jango@gmail.com'

id = 2和id = 4匹配搜索项(电话号码= 61477708777)。id = 5具有行id为4的相同电子邮件,id = 6具有行id为5的相同user_id。

2g32fytz

2g32fytz1#

递归查询是您所需要的,它可以帮助您声明性地表达为给定种子行添加其他行的推理:

with recursive r (id, user_id, phone_number, email) as (
  select u.id, u.user_id, u.phone_number, u.email
  from users u
  where u.phone_number = 61477708777 -- or any initial condition
  union
  select u.id, u.user_id, u.phone_number, u.email
  from r
  join users u on (
    r.email = u.email
    or r.user_id = u.user_id
    --or add whatever condition
  )
)
select * from r

fiddle

omqzjyyz

omqzjyyz2#

使用不同条件多次将表与其自身联接时出现问题。
尝试:

SELECT a.*
FROM users a
JOIN (SELECT user_id, COUNT(*)
FROM users 
GROUP BY user_id
HAVING count(*) > 1 ) b
ON a.user_id = b.user_id
union
SELECT a.*
FROM users a
JOIN (SELECT email, COUNT(*)
FROM users 
GROUP BY email
HAVING count(*) > 1 ) b
ON a.email = b.email

这个查询首先根据输入的user_id过滤行,然后检查任何匹配的电子邮件地址,也可以为phone_number添加union
fiddle

相关问题