-1

我有一个选择查询,但我希望在结果中也有几个计数作为列:计算与 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 |
+------+-------+------+------+---------+------+------+---------+
4

1 回答 1

1

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

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

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

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

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

如果我把你弄错了更好检查这个它有更多的解释

希望这会帮助你。

于 2012-05-15T11:20:07.913 回答