Mysql父id id子id关系

时间:2017-10-08 15:24:22

标签: mysql

这是我的表

id parent_key field key status
1  0          f1    fk1  1
2  0          f2    fk2  0
3  fk2        f3    fk3  1
4  fk3        f4    fk4  1
5  0          f5    fk5  1
6  fk5        f6    fk6  1
7  fk6        f7    fk7  1
8  fk7        f8    fk8  0
9  fk8        f9    fk9  1

现在我想使用mysql查询跟踪数据

id parent_key field key status
1  0          f1    fk1  1
5  0          f5    fk5  1
6  fk5        f6    fk6  1
7  fk6        f7    fk7  1

查看父行状态是否为0,则不会考虑所有相应的子字段。

2 个答案:

答案 0 :(得分:0)

假设表名和列。试试这个简单的查询

SELECT parent.id,parent.parent_key,parent.field,parent.status FROM parent   
as parent INNER JOIN child as child ON parent.id=child.id WHERE   
parent.status!=0

定义所需的列。

答案 1 :(得分:0)

创建表语句。

create table test (
  id int, 
  parent_key varchar(10),
  field varchar(10), 
  key1 varchar(10),
  status int
);

插入查询语句。

insert into test values (1,'0'  ,'f1','fk1',1);
insert into test values (2,'0'  ,'f2','fk2',0);
insert into test values (3,'fk2','f3','fk3',1);
insert into test values (4,'fk3','f4','fk4',1);
insert into test values (5,'0','f5','fk5',1);
insert into test values (6,'fk5','f6','fk6',1);
insert into test values (7,'fk6','f7','fk7',1);
insert into test values (8,'fk7','f8','fk8',0);
insert into test values (9,'fk8','f9','fk9',1);

查询:

set @status0 = ( select group_concat(key1) from test where status = 0);

select * from 
( select *, 
 if(find_in_set(parent_key,@status0) > 0, @status0 := concat(@status0,',',key1),@status0 ) as check_column
from test ) a 
where 
find_in_set(key1,check_column ) = 0

说明:

  1. 找到状态为0的所有key1并存储在@ status0。
  2. 找到所有父键并将其添加到@ status0变量。见子查询。
  3. 我们拥有需要从最终查询中删除的所有key1。
  4. 使用find_in_set(key1,check_column)= 0条件 删除这些数据。
相关问题