2015-11-18 46 views
1

這裏是結構我的表的如何計算有兩張郵政表時總票數?

// table1 
+----+-------+--------------------+ 
| id | color |  content  | 
+----+-------+--------------------+ 
| 1 | blue | it is a bad color | 
| 2 | red | it is a good color | 
| 3 | green | I don't like this | 
+----+-------+--------------------+ 

// table2 
+----+-------+---------------------+ 
| id | site |  description  | 
+----+-------+---------------------+ 
| 1 | stack | help to programmers | 
| 2 | google| everything you like | 
+----+-------+---------------------+ 

// votes 
+----+-----------+---------+-------+ 
| id | table_code| post_id | value | 
+----+-----------+---------+-------+ 
| 1 | 1  | 1  | 1 | // table1, post1, +1upvote  (blue) 
| 2 | 1  | 2  | -1 | // table1, post2, -1downvote (red) 
| 3 | 2  | 1  | 1 | // table2, post1, +1upvote  (stack) 
+----+-----------+---------+-------+ 

而且,這裏是我的查詢

select t3.*, (select sum(value) from votes v where t3.id = v.post_id) total_votes 
    from (
     select * from table1 
     union all 
     select * from table2 
    ) t3 

這裏是我的輸出

+----+-------+---------------------+-------------+ 
| id | color |  content  | total_votes | 
+----+-------+---------------------+-------------+ 
| 1 | blue | it is a bad color | 2   | // Problem (it should be 1) 
| 2 | red | it is a good color | -1   | 
| 3 | green | I don't like this | 0   | 
| 1 | stack | help to programmers | 2   | // Problem (it should be 1) 
| 2 | google| everything you like | 0   | 
+----+-------+---------------------+-------------+ 

正如你請參閱此^表格中的cal total_votes的錯誤是錯誤的。我該如何解決它?

說明:根據實際情況,我不能合併table1table2。所以,請不要告訴我你的結構是瘋狂的。

回答

1

你必須在UNION還指定table_code

select t3.*, 
     (select sum(value) 
     from votes v 
     where t3.id = v.post_id and 
       v.table_code = t3.table_code) total_votes 
    from (
     select *, 1 table_code from table1 
     union all 
     select *, 2 from table2 
    ) t3 

在相關子查詢中使用table_code我們可以從votes表選擇正確的價值觀。

+0

幹得好!似乎是正確的。我會查一下。不管怎樣,謝謝。 +1 – Shafizadeh