【问题标题】:Getting value from a parent row to child row, with a recursive MySQL query使用递归 MySQL 查询从父行到子行获取值
【发布时间】:2019-01-29 10:28:28
【问题描述】:

我想将父行中的值放在子行中,问题是所有内容都有多个级别。我给你看会更容易。

这是我所拥有的:

我想要类似的东西:

id | question_id | text
74 | 47          | Test answer
75 | 47          | Another answer
76 | 47          | Sub answer
77 | 47          | Sub sub answer

我想获取每个答案(行)的所有第一级父母的列表。 id 77 的顶级父级是 75,而 75 的 question_id 为 47,这正是我所需要的。因为这样我就可以 count() 来自 question_id 47 的总答案。

我调查了一下,尝试了以下代码:

SELECT @pv:=id AS id, answered_at, parent 
FROM qa_answers
JOIN (SELECT @pv:=75) AS tmp
WHERE parent = @pv

但这仅返回 id 75,我想向我展示所有内容。关于如何实现这一目标的任何想法?我不是 SQL 专家。

【问题讨论】:

  • 在 MySQL 8+ 中使用递归 CTE。
  • 任何链接可以帮助我理解它是什么?

标签: mysql sql recursive-query


【解决方案1】:

希望对你有帮助。

表结构

CREATE TABLE IF NOT EXISTS `products_t` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `parent_id` varchar(100) DEFAULT NULL,
  `sub_id` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `products_t` (`id`, `name`, `parent_id`, `sub_id`) VALUES
(74, 'category15', '47', NULL),
(75, 'category16', '47', NULL),
(76, 'category19', NULL, '75'),
(77, 'category20', NULL, '76'),
(80, 'category80', NULL, '50'),
(81, 'category81', '50', NULL);

查询

select  id,
        name,
        IFNULL(parent_id,'47' ) as parent_id
from    (select * from products_t
         order by parent_id, id) products_sorted,
        (select @pv := '47') initialisation
where   (find_in_set(parent_id, @pv) or find_in_set(sub_id, @pv) )
and     length(@pv := concat(@pv, ',', id))

这里,@pv := '47' 中指定的值应设置为要选择其所有后代的父级的 id。

结果

id  name        parent_id 
74  category15  47
75  category16  47
76  category19  47
77  category20  47

【讨论】:

  • 谢谢,但这不符合我的要求。但我想我理解你的逻辑,也许我可以调整并让它发挥作用
  • @rafamds 感谢您的评论,请检查编辑后的答案。
  • “试试这个”-答案总是很危险,因为它们很少包含一些解释。这使得 OP 和其他读者无法从中学习,因此请编辑您的答案并添加一些解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2022-01-20
  • 1970-01-01
  • 2015-10-21
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多