2012-05-15 96 views
-1

我有一個選擇查詢,但我想在結果中也有幾個計數作爲列:統計有多少t3行與t1行相關聯,多少t3行與t2行相關聯。結果應該有列:t1t3Count,t2t3Count。對於第一行t1T3Count應該等於5,和t2t3count從子查詢mysql很多計數

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

不是100%確定你在做什麼。請顯示您想要的輸出。 – eggyal

回答

1

嗯,如果我理解正確的話要算來自T1的所有項目的總髮生到這兩個T2和T3吧?

如果是這樣,所提供的數據必須導致

NAME1 = 5 {t2中2和T3 3}和 名稱2 = 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它有更多的解釋

希望這WIL我幫你。