php - 如何获得具有猫、子猫和 2 个表的条目总和

标签 php mysql

表 1:

catid   level   entries
   57       1         0
   58       2         5
   59       2         4
   84       1         0

表 2:

   id  parent      type
   58      57       cat
   59      57       cat 

我想获取子类别条目的 SUM 并将它们添加到父类别条目字段。在第一个表中,结果应为 9,其中 catid57

我该怎么做?

最佳答案

试试这个:

select a.*, b.sum_subcat from table1 a
inner join 
(
  SELECT t2.parent, sum(entries) sum_subcat
  FROM table1 t1 inner join table2 t2 
  on t1.catid = t2.id 
  group by t2.parent
)b on a.catid = b.parent
where a.catid = 57;

SQL DEMO HERE

关于php - 如何获得具有猫、子猫和 2 个表的条目总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543048/

相关文章:

php - 错误插入

mysql - 如何将本地 mysql 数据库连接到 MacBook Pro 中的 Apache 超集?

php - 范围方法的 where 子句中的 Laravel 数据透视表计数

php - 为什么我的 HttpPost 不起作用?

php - 无效配置 - yii\base\InvalidConfigException - Yii2

mysql - 如何通过 Asterisk 1.8.5 中的 cdr_adaptive_odbc.so 模块启用 CDR 日志记录?

php - Ajax Onchange 在 foreach 循环内

php - .css 样式表中的 mod_rewrite 图像现在需要绝对路径吗?

mysql - 如何让MySQL更高效的运行?

php - 更新声明无效