2014-09-12 89 views
1

我有一个包含以下字段(id,parent_id,name)的表'tags'。现在我已经在层次结构中设置了3个级别的限制,即:parent> child> subchild。子女不能有更多的孩子。所以我想查询检索记录,如:在mysql中获取父/子/子关系

家长数据 (如果父母有子)子数据 (如果孩子有subchild)subchild数据

回答

1

试着这么做:

SELECT tparent.id AS parent_id, 
     tparent.name AS parent_name, 
     tchild1.id AS child_id, 
     tchild1.name AS child_name, 
     tchild2.id AS subchild_id, 
     tchild2.name AS subchild_name 
FROM tags tparent 
     LEFT JOIN tags tchild1 
       ON tparent.id = tchild1.parent_id 
     LEFT JOIN tags tchild2 
       ON tchild1.id = tchild2.parent_id 

根据您的评论,你看以下的输出:

ID | PARENT | NAME 
1 |  0 | family 
2 |  1 | male 
3 |  2 | boy1 
4 |  2 | boy2 
5 |  1 | female 
6 |  5 | girl1 

我将认为IDS不会永远是我ñ这个顺序,如果他们的原因,问题解决:)

我不确定你可以直接在SQL中实现这一点,而无需添加一些额外的信息,将用于排序。例如,你可以添加另一列来连接parent-child-subchild的id。例如:

-- parent 
SELECT CONCAT(LPAD(id, 6, '0'), '-000000-000000') AS order_info, 
     id           AS id, 
     parent_id         AS parent, 
     name          AS name 
FROM tags 
WHERE parent_id = 0 
UNION 
-- child 
SELECT CONCAT_WS('-', LPAD(tparent.id, 6, '0'), 
         LPAD(tchild1.id, 6, '0'), 
         '000000'), 
     tchild1.id, 
     tparent.id, 
     tchild1.name 
FROM tags tparent 
     INNER JOIN tags tchild1 
       ON tparent.id = tchild1.parent_id 
WHERE tparent.parent_id = 0 
UNION 
-- subchild 
SELECT CONCAT_WS('-', LPAD(tparent.id, 6, '0'), 
         LPAD(tchild1.id, 6, '0'), 
         LPAD(tchild2.id, 6, '0')), 
     tchild2.id, 
     tchild1.id, 
     tchild2.name 
FROM tags tparent 
     INNER JOIN tags tchild1 
       ON tparent.id = tchild1.parent_id 
     INNER JOIN tags tchild2 
       ON tchild1.id = tchild2.parent_id 
ORDER BY 1 

请参阅the fiddle说明这一点。

在这里,我格式化的ID保持排序连贯。这意味着知道ID的最大长度(我在这里使用了6的长度),这从ID字段类型猜测是微不足道的。

+0

是的,我已经使用了这个,但是这使我得到了一个单一记录中的完整节点。即: 父 - >子1 - > subchild 父 - >子2 - > subchild 不过,我想找回这样的记录: 家长 孩子1 subchild 孩子2 subchild – user3093048 2014-09-13 09:43:52

+0

请添加样本输出在你的问题中清楚地说明,但如果我理解你的需求,那么你最好在你的表示层而不是SQL中做这件事。 – 2014-09-13 14:49:22

+0

以下是我想要生成的输出。当我搜索名为“家庭”的标签时,应按照以下顺序检索我的孩子和子孩子。 输出: 'ID,父,名称 1,0,家庭 2,1,雄性 3,2,请分享帮助 4,2,boy2 5,1,女性 6,5,girl1' 我可以通过使用联接解决方案在表示层中执行此操作,但为此我需要使用一些检查来组织数据。但是,如果有可能产生上面的输出,请你帮助我。在此先感谢 – user3093048 2014-09-13 20:56:11