The problem of mysql Multi-table continuous query

id   name   relation
1     n1       r1
2     n2       r2
3     n4       r1
4     n5       r1
5     n6       r2
6     n6       r1

the relation relationship of the table is shown above

where the relation field indicates the relationship between the current row and the name fields of other rows. For example, the data of name=n1 and name=n4,name=n5,name=n6 creates a "one-time connection" through R1. The data of name=n2 and name=n6 have a "one-time connection" through R2. N1 and N2, respectively, connect with N2 through R1 and R2, so I will define N1 and N2 as the "secondary connection relationship"

.

now I"m going to use sql to find out whether they were in a "secondary connection relationship"

.

the sql query written with thinkphp is as follows:

$where["jump_table.name"] = "n1";
$where["land_table.name"] = "n2";
$jump = M("relation")->alias("switch_table")
                ->join("LEFT JOIN relation AS jump_table ON switch_table.relation = jump_table.relation")
                ->join("LEFT JOIN relation AS land_table ON switch_table.relation = land_table.relation")
                ->where($where)
                ->field("switch_table.name")
                ->select();
                
                

the result of this query is empty.
ask God for advice on how to write this sql.

Mar.28,2021

then N1 and N2 have a secondary connection. I can't understand what this sentence means


ahem. I have a general understanding of your table relationship, that is, R1 is the same subordinate class, which is connected between the same subordinate class. But if user N6 belongs to both R1 and R2, it is connected, and all members of R1 and R2, to which N6 belongs, are connected to each other?


try to write a sql statement:

select name
from t
where t.relation in (
  select relation from t where t.name in ('n1', n2')
)
group by name 
having count(*) >= 2
where name not in ('n1', n2')

if the above statement returns a result, it means that there is a secondary connection


the logic is a bit tedious, let's take a look at it. The name fetched by sql below are all secondary connections

select group_concat(aaa.gb) 
from (select 
case when left(replace(aa.gb,bb.name,''),1)=',' 
    then right(replace(aa.gb,bb.name,''),char_length(replace(aa.gb,bb.name,''))-1)
when right(replace(aa.gb,bb.name,''),1)=','
    then left(replace(aa.gb,bb.name,''),char_length(replace(aa.gb,bb.name,''))-1)
else replace(replace(aa.gb,bb.name,''),',,',',') end gb,bb.name 
from (select group_concat(name) gb from t group by relation having count(1)>1) aa,
(select name from t group by name having count(1)>1) bb
where find_in_set(bb.name,aa.gb)) aaa group by aaa.name;
Menu