Mysql 将多个SQL计数放入单个结果集中

Mysql 将多个SQL计数放入单个结果集中,mysql,sql,sqlyog,Mysql,Sql,Sqlyog,大家好 我正在尝试做一些我认为在MYSQL上不可能的事情 我们有一个非常大的数据库,可以从中提取所创建产品的生产报告。目前,我们运行多个查询以获得这些结果,然后在将数据发送给任何需要报告的人之前,手动将数据传输到表中 有没有更简单的方法。我只问了一个问题 我运行的查询示例 a. SELECT count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "

大家好

我正在尝试做一些我认为在MYSQL上不可能的事情

我们有一个非常大的数据库,可以从中提取所创建产品的生产报告。目前,我们运行多个查询以获得这些结果,然后在将数据发送给任何需要报告的人之前,手动将数据传输到表中

有没有更简单的方法。我只问了一个问题

我运行的查询示例

a. SELECT count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>";
b. SELECT count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>";
c. SELECT count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>";
我想要的结果的例子

产品A产品B产品C 500 500 500
我认为您需要使用存储过程

Create StoredProcedure SP_Name_1
As
Beign
Declare @id1 int,@id2 int,@id3 int;
SELECT @id1 = count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>";
SELECT @id2 = count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>";
SELECT @id2 = count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>";

select  @id1 as ProductA ,@id2 as ProductB ,@id3 as ProductC
End
谢谢,
塔哈

您可以使用UNION ALL:

SELECT 'ProductA', count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>"
UNION ALL
SELECT 'ProductB', count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>"
UNION ALL
SELECT 'ProductC', count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>";

当然,您可以复制选择其他4种产品或任何数量的您想要的-

您可以将所有内容放入Select子句中,如下所示:

Select
(SELECT count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountA
(SELECT count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountB
(SELECT count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountC
这样,您将获得如下输入:

Select
(SELECT count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountA
(SELECT count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountB
(SELECT count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountC
CountA CountB CountC 500 500 500
您可以稍后轻松添加更多计数

您只有3种产品吗?我实际上有7种不同的产品,具有多种产品状态,我必须检查。如果我能以我所需要的方式运行查询的基础知识,那么剩下的将很容易扩展到n个产品数量。@FreshPrinceOfSO-OP在评论中指出,他/她大约有7个这样的表。@PM77-1 about是一个很好的编程需求词。@FreshPrinceOfSO如果你看到评论的时间大致相同,此外,创建者还更新了评论,这也需要额外的时间。这里的每个答案都不是n数量的比例。存储过程是执行此任务的最佳方式抱歉,我在手机上发帖:-/