如果表中存在行,MySQL 将创建一个总和

标签 mysql

我有这样的声明:

select * from category a 
inner join category b on a.row=b.relatedRow 
inner join category c on b.row=c.relatedRow where a.row=?

我想像这样获得“级别”的数量:

如果a有行,level=1,如果b有行,level=2,如果c 有行,level=3

我该怎么做?

示例

row, relatedRow

1,null

2,1

3,2

4,3

5,2

6,5

因此,1 与任何行都不相关,2 与 1 相关,3 与 2 相关,依此类推...

如果 row=1,则级别 1 存在,因为 1 存在

级别 2 存在,因为 2 与 1 相关

级别 3 存在,因为 3 和 5 与 2 相关

级别 4 存在,因为 6 与 5 相关,4 与 3 相关

因此这棵树下降了 4 层。

最佳答案

尝试一些类似的事情:

select 
    sum(case when not b.relatedRow  is null then 1 else 0 end) as level1_total 
    sum(case when not c.relatedRow  is null then 1 else 0 end) as level2_total
from category a 
left join category b on a.row=b.relatedRow 
left join category c on b.row=c.relatedRow where a.row=?

当然,您可以修改case中的条件以适合您对有行的定义

关于如果表中存在行,MySQL 将创建一个总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226683/

相关文章:

php - 在 MySQL 非空字段上创建 DateTime 对象

java - 我的查询中的 sql 语法错误

mysql - 将变量插入 SQL 语句

php - 使用 group by 子句对两列数据进行分组

mysql - Node js 使用连接池和多个参数调用mysql中的存储过程

php - 如何通过3+张表建立Laravel Eloquent模型

用户 friend 的 Php 爆炸或唯一 Mysql 表?

mySQL正则表达式选择字符串和增量数字

php - sql - 如何在 MySql 中截断多个表?

php - 表名作为模型 Codeigniter 中的变量