2016-05-08 56 views
0

我的數據庫來完成Mysql的連接4臺可以將其在一個查詢

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 

我只能做了很多不同的查詢,但我認爲這是不是很好的做法。

回答

0

如果所有的表都嚴格相關,您可以使用內部聯接

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 
+0

怎麼樣計數和category_group命令? – splash58

+0

@ splash58我已經根據問題更新了答案 – scaisEdge

+0

,應該是兩個計數器 - 主題和評論 – splash58