从单个表中获取mysql中的类别子类别

时间:2016-12-20 10:44:35

标签: mysql join

我有一张下面给出的表格。我想获取父母所在的所有类别。

id   name    parent
1    test1   0
2    test2   0
3    test3   1
4    test4   3

当我传递id = 4

时,它应该给出以下结果
test4 > test3 > test1

I try the below query: 

select a.* 
  from merchant_service_category a
     , merchant_service_category b 
 where a.id = b.parent

但是它给出了整个表的通用结果。我只需要那些id = 4的记录。 该查询仅提供2条记录test4>仅限test3。

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你想要获取一条记录并使用它的父母:一张在同一张桌子里的记录。因此,您需要在同一个表上加入结果。试试这个:

SELECT child.* FROM `merchant_service_category` child
JOIN `merchant_service_category` parent ON child.parent = parent.id
WHERE child.id = 4;

使用此查询,您将获取ID为4的记录,并将结果与​​ID为3的父类别相结合。

答案 1 :(得分:-1)

我找到了答案。以下是查询。

SELECT   T2.id,T2.name,T2.parent
FROM (
SELECT
    @r AS _id,
    (SELECT @r := parent FROM merchant_service_category WHERE id = _id) AS parent_id    FROM
    (SELECT @r := 4) vars,
    merchant_service_category h
WHERE @r <> 0) T1
JOIN merchant_service_category T2
ON T1._id = T2.id
相关问题