gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:02:26 25 4
gpt4 key购买 nike

我的数据库

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com