MySQL:如何查询列并在同一个表中包含来自相关列的信息?

标签 mysql join count group-by

在 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 值,将返回一个 RootIdRootName 只有当确实有两 (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/

相关文章:

MySQL (JDBC) - 基于列值的排行榜排名

php - 测试日期是否在单个查询中重叠

sql - 在 SQL 连接方面需要帮助

R - 按中断切割并按组计算出现次数

php - 我想通过 Dreamweaver 将文件 uploader 添加到现有内容 uploader - 将 pdf 上传到特定文件夹,在数据库中生成 pdf 的 url

PHP/Mysql array_pop 缺少第一个值

php - 无法通过 codeigniter 中的 join 获取记录

mySQL JOIN 具有特定列的同一个表

python - 变换计数连续整数

ios - estimatedAssetCount 返回错误的计数