[英]Counts of two fields in different table with grouping not working
I have three table a, b and c in mysql. 我在mysql中有三个表a,b和c。 a has events, b has ticket categories for each event of a, and c has tickets each of b.
a具有事件,b具有a的每个事件的票证类别,c具有b的每个票证。 So a pure relational datbase.
因此是一个纯粹的关系数据库。 What i'm trying to find out is the count of total ticket categories and total tickets each of the event a has.
我想找出的是每个事件都有的总门票类别和总门票的数量。
I had tried like this: 我曾这样尝试过:
SELECT a. * , COUNT( b.at_id ) AS totTktCat, COUNT( c.bt_id ) AS totTkts FROM a_table a JOIN b_table b USING ( at_id ) JOIN c_table c USING ( bt_id ) GROUP BY a.at_id
but no luck, the totals are wrong. 但没有运气,总数是错误的。
A little help from the mysql gurus will help. 来自mysql专家的一些帮助将有所帮助。
I have added an sql fiddle: http://sqlfiddle.com/#!9/ec8b0/1 . 我添加了一个SQL提琴: http : //sqlfiddle.com/# !9/ec8b0/1。
I'm getting total like this 我总这样
at_id at_cat at_event totTktCat totTkts 1 1 aevent1 6 6 2 2 aevent2 2 2which is wrong.
\nat_id at_cat at_event COUNT(bt_ticktgrp) COUNT(ct_tickets)For the sql fiddle: http://sqlfiddle.com/#!9/ebc9ea6at_id at_cat at_event COUNT(bt_ticktgrp)COUNT(ct_tickets)\n2 2 aevent2 2 4
2 2事件2 2 4\n
As per your given description, i have written query like this.. 根据您给定的描述,我已经写过这样的查询。
SELECT a.at_id,a.at_cat,a.at_event,count(*) as bt_ticktgrp,(SELECT count(*) FROM `b_table` b JOIN `c_table` c ON c.bt_id=b.bt_id where b.at_id=a.at_id) as ct_tickets FROM `a_table` a JOIN `b_table` b
ON a.at_id=b.at_id
GROUP BY a.at_cat;
Here i have grouped outer one with table a
and inner one with table c
by mapping it with table b
. 在这里,我通过将其与
table b
映射,将外部的table a
与table a
分组,内部的1与table c
分组。
ie With each id of table a
it joins table b
and table c
. 即,使用
table a
每个ID将table b
和table c
。
Hope this solves your query. 希望这可以解决您的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.