如何在mysql中获取上一个子关系

时间:2018-08-24 10:21:02

标签: mysql sql database relationship

我的表结构:

--------------------------
|Categories              |
--------------------------
|id    |parent_id|title  |
--------------------------
|1     |null     |t1     |
--------------------------
|2     |1        |t2     |
--------------------------
|3     |1        |t3     |
--------------------------
|4     |2        |t4     |
--------------------------
|5     |4        |t5     |
--------------------------
|6     |null     |t6     |
--------------------------

我需要找出给定项目/类别与其根项目/类别之间有多少项目,包括指定项目和根项目。

例如,在此表中,title=t5的计数为4(t1-> t2-> t4-> t5)。

MySQL版本:5.6.21

3 个答案:

答案 0 :(得分:1)

如果您的mysql版本支持cte,则可以尝试使用 CTE递归

模式(MySQL v8.0)

CREATE TABLE  Categories(
   id INT,
   parent_id INT,
   title VARCHAR(50)
);



INSERT INTO Categories VALUES (1,null,'t1');
INSERT INTO Categories VALUES (2,1   ,'t2');
INSERT INTO Categories VALUES (3,1   ,'t3');
INSERT INTO Categories VALUES (4,2   ,'t4');
INSERT INTO Categories VALUES (5,4   ,'t5');
INSERT INTO Categories VALUES (6,null,'t6');

查询#1

WITH RECURSIVE  cte1 AS (
  SELECT id,parent_id,title
  FROM Categories
  where title = 't5'
  UNION ALL
  SELECT cte1.id,c.parent_id,c.title
  FROM cte1 INNER JOIN Categories c
  on c.id = cte1.parent_id
)
SELECT id,GROUP_CONCAT(title separator '->') result
FROM cte1
GROUP BY id;

| id  | result         |
| --- | -------------- |
| 5   | t5->t4->t2->t1 |

View on DB Fiddle

答案 1 :(得分:0)

在MySQL parent_id为空):

DROP FUNCTION IF EXISTS depth;
DELIMITER \\
CREATE FUNCTION `depth`(item VARCHAR(20)) RETURNS int(11)
   DETERMINISTIC
BEGIN
 DECLARE d INT DEFAULT 1;
 DECLARE p INT;
 SELECT COALESCE(parent_id, 0) INTO p FROM categories WHERE title = item;
 WHILE p != 0 DO
   SET d = d + 1;
   SELECT COALESCE(parent_id, 0) INTO p FROM categories WHERE id = p;
 END WHILE;
 RETURN (d);
END \\
DELIMITER ;

SELECT depth('t1'), depth('t2'), depth('t3'), depth('t4'), depth('t5'), depth('t6')

输出:

depth('t1')     depth('t2')     depth('t3')     depth('t4')     depth('t5')     depth('t6')     
1               2               2               3               4               1

答案 2 :(得分:-1)

尝试一下:

SELECT (MAX(ID) - 1) as ParentID
FROM your_table;

如果这不正确,那么我不理解您的问题,对不起。