1
在每個表中都有許多具有數量的行。像這樣,我在每張表中都有不同數量的金額。每個表字段名稱是不同的。我怎樣才能得到一個查詢中的四個表中的所有值的總和?有什麼方法嗎?如何從單個查詢中的四個不同表中獲得總數
在每個表中都有許多具有數量的行。像這樣,我在每張表中都有不同數量的金額。每個表字段名稱是不同的。我怎樣才能得到一個查詢中的四個表中的所有值的總和?有什麼方法嗎?如何從單個查詢中的四個不同表中獲得總數
你試過類似的東西嗎?
select sum(val) from (
select sum(col1) as val from table1 where criteria1 = 'x'
union all
select sum(col2) from table2 where criteria2 = 'y'
union all
select sum(col3) from table3 where criteria3 = 'z'
union all
select sum(col4) from table4 where criteria4 = 'w'
) newTbl
使用派生表 - 你可能想做這樣的事情,所以你得到所有結果在一行!
select
u.user_count,
c.country_count
from
(
select count(*) as user_count from users where username like 'f%'
) u
join
(
select count(*) as country_count from country
) c;
更comlpex例如:http://pastie.org/921407
在一些數據庫中的結合命令自動刪除重複的行。如果你從兩個表中得到相同的總和,這將是一個問題。使用'union all'來保留重複項。 – BenV 2010-04-15 13:47:38
好點。編輯我的答案。 – MJB 2010-04-15 13:49:22
我用這種方式,我得到了這種類型的錯誤。 #1248 - 每個派生表必須有自己的別名 是的,它是這樣嗎?還有一件事'union all'在mysql中工作? – Karthik 2010-04-15 13:52:12