2014-03-25 51 views
1

我已经得到了下面的mysql脚本,它获取了几个表中的总行数并将它们加在一起。然后我想在下一个执行的另一个脚本中使用这个“Total”。在sql脚本中使用变量?

我想显示总数的百分比。显然以下不起作用,因为“总计”不被认可。我如何使用下一个陈述的第一个陈述的结果?

select (
(select count(*) from t1) + 
(select count(*) from t2) + 
(select count(*) from t3) + 
(select count(*) from t4) + 
(select count(*) from t5) + 
(select count(*) from t6)) As Total; 


select 
round((count(greater10)/Total * 100),2) As greater10, 
round((count(8to10)/Total * 100),2) As 8to10, 
round((count(6to8)/Total * 100),2) As 6to8, 
round((count(4to6)/Total * 100),2) As 4to8, 
round((count(2to4)/Total * 100),2) As 2to4, 
round((count(halfto2)/Total * 100),2) As halfto2, 
round((count(lesshalf)/ Total * 100),2) As lesshalf 
from t7; 

回答

1

你可以节省使用SELECT...INTO语法结果为user variable

select (
(select count(*) from t1) + 
(select count(*) from t2) + 
(select count(*) from t3) + 
(select count(*) from t4) + 
(select count(*) from t5) + 
(select count(*) from t6)) INTO @Total; 


select 
round((count(greater10)/@Total * 100),2) As greater10, 
round((count(8to10)/@Total * 100),2) As 8to10, 
round((count(6to8)/@Total * 100),2) As 6to8, 
round((count(4to6)/@Total * 100),2) As 4to8, 
round((count(2to4)/@Total * 100),2) As 2to4, 
round((count(halfto2)/@Total * 100),2) As halfto2, 
round((count(lesshalf)/ @Total * 100),2) As lesshalf 
from t7; 

只要会话保持活动状态,用户变量就会保持该值。所以你可以在随后的查询中使用该变量,只要它在同一个数据库连接中。

另一种选择是将总查询作为子查询,因此它立即可用。

select 
round((count(greater10)/t.Total * 100),2) As greater10, 
round((count(8to10)/t.Total * 100),2) As 8to10, 
round((count(6to8)/t.Total * 100),2) As 6to8, 
round((count(4to6)/t.Total * 100),2) As 4to8, 
round((count(2to4)/t.Total * 100),2) As 2to4, 
round((count(halfto2)/t.Total * 100),2) As halfto2, 
round((count(lesshalf)/ t.Total * 100),2) As lesshalf 
from (
    select (
    (select count(*) from t1) + 
    (select count(*) from t2) + 
    (select count(*) from t3) + 
    (select count(*) from t4) + 
    (select count(*) from t5) + 
    (select count(*) from t6)) AS Total) 
) AS t, 
t7; 
+0

谢谢 - 正是我在找的东西。很棒! – Greg