查找连接对

时间:2019-11-05 23:22:10

标签: mysql sql

假设我们在mySQL数据库中有一个表,其中fname与另一个fname(BB_Connection_name)有连接,我们希望有一个查询来查找一对在彼此之间找到连接的朋友。

例如 Sidharth和Asim都有BBid和BB_Connection_ID

enter image description here

我一直在寻找类似的父亲,儿子和孙子问题,但是并不是每个父亲都有一个儿子,因此内在的联系使他们更容易解决。我尝试使用它,但是没有用。

这里我需要检查每个fname(A)的BB_Connection_ID,然后相应的fname是否具有A的BBid作为他的BB_Connection_ID。

将要选择的对应该像Sidharth <-> Asim 我们需要找到彼此具有连接ID的配对。

================================================ =========================

Code for recreation of the table:
-----------------------------------------------------------------------------
create table world.bigbb(
BBid int not null auto_increment,
fname varchar(20) NOT NULL,
lname varchar(30),
BBdays int not null,
No_of_Nom int,
BB_rank int not null,
BB_Task varchar(10),
BB_Connection_ID int,
BB_Connection_name varchar(10),
primary key (BBid)
);


insert into world.bigbb (fname, lname, BBdays, No_of_Nom, BB_rank, BB_Task, BB_Connection_ID, BB_Connection_name)
values 
('Sidharth', 'Shukla', 40, 4, 2, 'Kitchen', 11, 'Asim'),
('Arhaan', 'Khan', 7, 1, 9, 'Kitchen', 16, 'Rashmi'),
('Vikas', 'Bhau', 7, 1, 8, 'Bedroom', 11, 'Asim'),
('Khesari', 'Bihari', 7, 1, 12, 'Kitchen', 9, 'Paras'),
('Tehseem', 'Poonawala', 7, 1, 11, 'Washroom', 12, 'Khesari'),
('Shehnaaz', 'Gill', 40, 4, 4, 'Washroom', 9, 'Paras'),
('Himanshi', 'Khurana', 7, 0, 7, 'Bedroom', 8, 'Shefali'),
('Shefali', 'Zariwala', 7, 1, 10, 'Bedroom', 1, 'Sidharth'),
('Paras', 'Chabra', 40, 3, 1, 'Bathroom', 10, 'Mahira'),
('Mahira', 'Sharma', 40, 4, 5, 'Kitchen', 9, 'Paras'),
('Asim', 'Khan', 40, 3, 3, 'Bathroom', 1, 'Sidharth'),
('Arti', 'Singh', 40, 5, 6, 'Captain', 1, 'Sidharth'),
('Sidharth', 'Dey', 35, 6, 16, 'None', 14, 'Shefali'),
('Shefali', 'Bagga', 38, 5, 15, 'None', 13, 'Sidharth'),
('Abu', 'Fifi', 22, 5, 17, 'None', 11, 'Asim'),
('Rashmi', 'Desai', 38, 5, 13, 'None', 17, 'Debolina'),
('Debolina', 'Bhattacharjee', 38, 5, 14, 'None', 16, 'Rashmi'); 

1 个答案:

答案 0 :(得分:0)

一种解决方案是自联接表:

select
    b1.fname name1,
    b2.fname name2
from bigbb b1
inner join bigbb b2
    on  b1.BB_Connection_ID = b2.BBid 
    and b2.BB_Connection_ID = b1.BBid 
    and b1.BBid < b2.BBid

这将为您提供每对一条记录,该记录在第一列中具有最小的BBid

demo on DB Fiddle 及其示例数据将返回:

name1    | name2   
:------- | :-------
Sidharth | Asim    
Paras    | Mahira  
Sidharth | Shefali 
Rashmi   | Debolina