在 MySQL 中,我有一个这样的表:
+-----------------------+
| Assets |
+-----------------------+
| Id | Name | RootId |
+----+---------+--------+
| 1 | Asset A | 1 |
+----+---------+--------+
| 2 | Asset B | 2 |
+----+---------+--------+
| 3 | Asset C | 3 |
+----+---------+--------+
| 4 | Asset D | 2 |
+----+---------+--------+
| 5 | Asset E | 3 |
+----+---------+--------+
| 6 | Asset F | 3 |
+----+---------+--------+
这不是最好的表结构,我知道......但我现在坚持使用它。
我正在尝试编写一个查询,给定一个 Id
值,将返回一个 RootId
和 RootName
只有当确实有两 (2) 行具有相同的 RootId
。否则这些列应该为 NULL。
因此,使用上表,如果给定的 Id
为 4,则查询应返回:
+----------------------------------+
| Assets |
+----------------------------------+
| Id | Name | RootId | RootName |
+----+---------+--------+----------+
| 4 | Asset D | 2 | AssetB |
+----+---------+--------+----------+
但是如果给定任何其他 Id
值,例如 5,它应该返回:
+----------------------------------+
| Assets |
+----------------------------------+
| Id | Name | RootId | RootName |
+----+---------+--------+----------+
| 5 | Asset E | null | null |
+----+---------+--------+----------+
如有任何帮助,我们将不胜感激。我认为它将需要一个带有 COUNT 和可能的 GROUP BY 的子查询,但我真的不确定如何表达它......
提前致谢!
最佳答案
下面应该实现这个逻辑:
select id, name,
(case when cnt = 2 then rootid end) as rootid,
(case when cnt = 2 then ari.name end) as rootname
from assets a join
(select rootid, count(*) as cnt
from assets a
group by rootid
) ri
on a.rootid = ri.rootid left join
assets ari
on a.rootid = ari.id
where id = 4;
您也可以这样做:
select a.id, a.name,
(case when a.cnt = 2 then a.rootid end) as rootid,
(case when a.cnt = 2 then ari.name end) as rootname
from (select a.*,
(select count(*) from assets a2 where a2.rootid = a.rootid) as cnt
from assets a
where id = 4
) a left join
assets ari
on a.rootid = ari.id;
如果没有完整的聚合,这会表现得更好。
Here是说明它们的 SQL Fiddle。
关于MySQL:如何查询列并在同一个表中包含来自相关列的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592163/