gpt4 book ai didi

mysql - 用于选择子项和父项的 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 03:35:36 26 4
gpt4 key购买 nike

我有一个包含 2 个字段的 mysql 表“taxonomy_term_hierarchy”。

tid -- 主键:术语的 taxonomy_term_data.tid。
parent -- 主键:术语父项的 taxonomy_term_data.tid。 0 表示没有父级。

我需要为某个学期获取 1 级子项,但如果它没有子项,则比为其父项获取子项。像这样的东西:

SELECT down.tid FROM taxonomy_term_hierarchy down WHERE down.parent=60
IF ( COUNT(down.tid) = 0 ) THEN
SELECT current.tid FROM taxonomy_term_hierarchy current
WHERE current.parent=
(SELECT its.parent FROM taxonomy_term_hierarchy its
WHERE its.tid=60)

我可以在单个查询中完成吗?

最佳答案

不幸的是,我认为这对于一个查询是不可能的,因为您需要一个 IF 语句来确定要使用哪个查询。但是,您可以创建一个存储过程来为您处理逻辑,并通过将 tid 传递给它来调用它。这是我创建的存储过程:

CREATE PROCEDURE getChildren(in _tid int)
BEGIN

DECLARE hasChildren BIT;

SET hasChildren = EXISTS (
SELECT ''
FROM taxonomy_term_hierarchy tth
WHERE tth.parent = _tid
);

IF hasChildren THEN
BEGIN
SELECT tid, parent
FROM taxonomy_term_hierarchy
WHERE parent = _tid;
END;
ELSE
BEGIN
SELECT tth3.tid, tth3.parent
FROM taxonomy_term_hierarchy tth1
INNER JOIN taxonomy_term_hierarchy tth2 ON tth1.parent = tth2.tid
INNER JOIN taxonomy_term_hierarchy tth3 ON tth2.tid = tth3.parent
WHERE tth1.tid = _tid;
END;
END IF;

END//

我在 this sql fiddle 上创建了架构这样您就可以自己测试一下。

关于mysql - 用于选择子项和父项的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22135080/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com