【问题标题】:How to get last child relation in mysql如何在mysql中获取最后一个子关系
【发布时间】:2018-08-24 10:21:01
【问题描述】:

我的表结构:

--------------------------
|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

【问题讨论】:

  • 你用的是什么版本的 MySQL?
  • @gordon-linoff: 5.6.21
  • @AliMohammadi 你会考虑更新 mysql 版本以支持 cte 吗? cte 递归会更容易实现。
  • @D-Shih 我不能,因为在主机服务器上。但是你能告诉我cte怎么做吗?

标签: mysql sql database relationship


【解决方案1】:

如果你的mysql版本支持cte你可以尝试使用CTE Recursion制作。

架构 (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

【讨论】:

【解决方案2】:

在 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

【讨论】:

    猜你喜欢
    • 2022-11-23
    • 2012-12-21
    • 2021-05-29
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多