Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从单个表中获取mysql中的类别子类别_Mysql_Join - Fatal编程技术网

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

从单个表中获取mysql中的类别子类别,mysql,join,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_

我有一张桌子在下面。我想获取父级所在的所有类别

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的记录。
查询只提供了两条记录test4>test3 only。

如果我理解正确,您希望获取一条记录并与其父记录一起获取:一条位于同一个表中的记录。因此,您需要将结果连接到同一个表上。试试这个:

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的类别连接起来。

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

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

MySQL不支持“开箱即用”的递归。选择包括编写存储过程、尽可能频繁地将邻接列表连接到自身、切换到替代模型(如嵌套集)或在应用程序级代码中处理递归逻辑,MySQL将在MySQL 8中获得递归CTE查询。这对于只有两个级别的层次结构非常有用Galago,它只提供1条记录,其中child.id为4。在到达父级0之前,我需要所有这些类别。因此,应该涵盖父母的所有层面。查询应该检查是否有父项,获取它,直到它到达父项0。当我不理解您的问题时。是否要返回ID为4的记录以及ID不是0的较低父ID的记录?