Mysql join 4个表可以在一个查询中完成吗

标签 mysql database

我的数据库

category_group(id,name)
category(id,name,cat_group_id)
topic(id,name,cat_id)
comment(id,name,topic_id)

我想要得到:

Category Group 1
=====================
Category 1
Count topic | Count comment
-------------------
Category 2
Count topic | Count comment


Category Group 2
=====================
Category 3
Count topic | Count comment
-------------------
Category 4
Count topic | Count comment

我只能处理很多不同的查询,但我认为这不是一个好的做法。

最佳答案

如果所有表都严格相关,则可以使用内连接

    select a.*, b.*, c.*, d.*
    from category as a
    inner join category_group as b on a.cat_group_id = b id
    inner join topic as c on a.id = c.cat_id
    inner join comment as d.topic_id = c.id

其他需要使用左连接的地方

那么对于你的情况,你可以这样做

    select b.name,  a.name, count(d.*) as count_commect, count(c.*) as count_topic
    from category as a
    inner join category_group as b on a.cat_group_id = b id
    inner join topic as c on a.id = c.cat_id
    inner join comment as d.topic_id = c.id
    group by a.name, b.name
    order by a.name, b.name

关于Mysql join 4个表可以在一个查询中完成吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099137/

相关文章:

mysql - Sql - 重复键更新

mysql 在给定其他值的约束条件下选择总和最大的记录

mongodb - open edx如何将类(class)内容数据存储到mongo数据库中?

php - 将 id 变量传递给数据库以编辑信息的问题

sql - 如何查找数据库 Teradata 中具有特定列名的所有表?

sql - 字符串 '{?District}' 在 SQL 中的计算结果是什么

database - Java DB 位置设置不正确 - netbeans

Mysql不能分配外键?

php - Doctrine2 和 MySQL 分区

mysql - SQL 在 2 列中选择不同的值,无论其顺序如何?