Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在sql脚本中使用变量?_Mysql - Fatal编程技术网

Mysql 在sql脚本中使用变量?

Mysql 在sql脚本中使用变量?,mysql,Mysql,我有下面的mysql脚本,它获取几个表中的行总数并将它们相加。然后我想在下一步执行的另一个脚本中使用这个“Total” 我想显示计数占总数的百分比。很明显,由于未确认“总计”,以下内容不起作用。如何在下一条语句中使用第一条语句的结果 select ( (select count(*) from t1) + (select count(*) from t2) + (select count(*) from t3) + (select count(*) from t4) + (select coun

我有下面的mysql脚本,它获取几个表中的行总数并将它们相加。然后我想在下一步执行的另一个脚本中使用这个“Total”

我想显示计数占总数的百分比。很明显,由于未确认“总计”,以下内容不起作用。如何在下一条语句中使用第一条语句的结果

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;

您可以使用语法将结果保存到文件中

只要会话保持活动状态,用户变量就会保持该值。因此,您可以在后续查询中使用该变量,只要它位于同一数据库连接中

另一个选项是将total查询作为子查询执行,以便它立即可用

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;

谢谢-正是我想要的。很好!
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;