mysql很多来自子查询的计数

时间:2012-05-15 08:57:25

标签: mysql sql

我有一个选择查询,但我想在结果中还有几个计数作为列:计算与t1行相关的t3行数和与t2行相关的t3行数。结果应该有列:t1t3Count,t2t3Count。对于第一行,t1T3Count应该等于5,并且t2t3count

create table t1 (id int, name text);
insert into t1 values(1, 'name1');
insert into t1 values(2, 'name2');
create table t2 (id int, t1Id int, name text);
insert into t2 values(1, 1, 't2name1');
insert into t2 values(2, 1, 't2name2');
insert into t2 values(3, 2, 't2name3');
create table t3 (id int, t2Id int, name text);
insert into t3 values(1, 1, 't3name1');
insert into t3 values(2, 1, 't3name2');
insert into t3 values(3, 1, 't3name3');
insert into t3 values(4, 2, 't3name3');
insert into t3 values(5, 2, 't3name3');
insert into t3 values(6, 3, 't3name3');

   mysql> select * from t1 join t2 on(t1.id=t2.t1Id) join t3 on(t2.id=t3.t2Id);
+------+-------+------+------+---------+------+------+---------+
| id   | name  | id   | t1Id | name    | id   | t2Id | name    |
+------+-------+------+------+---------+------+------+---------+
|    1 | name1 |    1 |    1 | t2name1 |    1 |    1 | t3name1 |
|    1 | name1 |    1 |    1 | t2name1 |    2 |    1 | t3name2 |
|    1 | name1 |    1 |    1 | t2name1 |    3 |    1 | t3name3 |
|    1 | name1 |    2 |    1 | t2name2 |    4 |    2 | t3name3 |
|    1 | name1 |    2 |    1 | t2name2 |    5 |    2 | t3name3 |
|    2 | name2 |    3 |    2 | t2name3 |    6 |    3 | t3name3 |
+------+-------+------+------+---------+------+------+---------+

1 个答案:

答案 0 :(得分:1)

好吧,如果我理解正确,你想要计算从t1到t2和t3的所有项目的总出现次数吗?

如果是这样,提供的数据必须导致

name1 = 5 {在t2中为2,在t3中为3}和 name2 = 3 {在t2中为1,在t3中为2}

如果以上是您想要的,那么这就是您想要的

SELECT 
      t1.id, t1.name, 
      COALESCE( t2Counts.t2Count, 000000 ) + COALESCE( t3Counts.t3Count, 000000 ) AS total_occurences_in_t2_and_t3
   FROM
      ( SELECT @t2Countt := 0,
               @t3Countt := 0
        ) sqlvars,
      t1
        LEFT JOIN ( SELECT t1Id, COUNT(*) AS t2Count
                       FROM t2
                       GROUP BY t1Id ) AS t2Counts
           ON t1.id = t2Counts.t1Id

        LEFT JOIN ( SELECT t2Id, COUNT(*) AS t3Count
                       FROM t3
                       GROUP BY t2Id ) AS t3Counts
           ON t1.id = t3Counts.t2Id

如果我错了你更好Check this它有更多的解释

希望这会对你有所帮助。