2017-10-08 122 views
0

这里是我的表Mysql的父ID子ID关系

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,那么所有相应的子场不会被考虑。

回答

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 

定义需要的列。

+0

我也想到了这一点,但是这只能获取父项的直接子项,而不是父项下的整个递归子树“树”(直到已达到叶或状态= 0) – Progman

+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. 查找@ STATUS0均具有key1的状态= 0和存储。
  2. 查找所有父键并将其添加到@ status0变量。请参阅子查询。
  3. 我们拥有所有需要从最终查询中删除的key1。
  4. 使用find_in_set(key1,check_column)= 0条件到 删除这些数据。
+0

这对你有帮助吗? –