在同一表中显示子关系和父关系(如果有)

  • 本文关键字:关系 如果 显示 mysql sql
  • 更新时间 :
  • 英文 :


我有这个表

| id |parent|name|
| 1  | NULL |  E |
| 2  | NULL |  B |
| 3  | 5    |  U |
| 4  | 5    |  X |
| 5  | NULL |  C |
| 6  | NULL |  A |

我想要按父母姓名排序的所有ID的列表,无论他们是否有父母:

| id |parent|name|has_child|
| 6  | NULL |  A |    0    |
| 2  | NULL |  B |    0    |
| 5  | NULL |  C |    1    |
| 3  | 5    |  U |    0    |
| 4  | 5    |  X |    0    |
| 1  | NULL |  E |    0    |

可能吗?

我尝试了很多事情,但从未得到正确的答案,而且我真的不知道如何添加"has_child"列

SELECT
t1.parent,
t2.name
FROM tablename AS t1
INNER JOIN
(
SELECT MIN(id) AS id, parent
FROM tablename
GROUP BY parent
) AS t22 ON t22.id = t1.id AND t1.parent = t22.parent
INNER JOIN tablename AS t2 ON t1.parent = t2.id;

我会在这里使用自加入:

SELECT DISTINCT
t1.id,
t1.parent,
t1.name,
1 - ISNULL(t2.id) has_child
FROM tablename t1
LEFT JOIN tablename t2
ON t1.id = t2.parent
ORDER BY
t1.id;

此处使用的联接条件(将作为父级的给定记录与一个或多个子记录进行匹配(是当前id也是其他一些记录的parent。 请注意,我们需要在此处SELECT DISTINCT,因为给定的父级可能与多个子记录匹配。

您可以使用自联接 - 因为您想要父级的名称而不是 id - 以及用于排序的coalesce()

select t.*,
(case when exists (select 1 from t tc where tc.parent = t.id)
then 1 else 0
end)
from t left join
t tp
on t.parent = tp.id
order by coalesce(tp.name, t.name),   -- group rows by the parent, if any
(tp.name is null) desc,      -- put parent first
t.name;                      -- order by children

我希望你觉得这个答案有点用。子查询获取父项的不同 id,并排除空白填充。

SELECT *,
CASE WHEN id IN (SELECT DISTINCT parent
FROM tablename
WHERE parent IS NOT NULL)
THEN '1' ELSE '0'
END AS has_child
FROM tablename 
ORDER BY name;
SELECT t1.id, t1.parent, t1.name, MAX(t2.parent is not null) has_child
FROM table t1
LEFT JOIN table t2 ON t1.id = t2.parent_id
GROUP BY t1.id, t1.parent, t1.name

最新更新