Mysql sql:在sql select查询中获取稍微修改的查询的计数?

Mysql sql:在sql select查询中获取稍微修改的查询的计数?,mysql,sql,Mysql,Sql,我们有一个包含以下列的images表:-1 imageId、2 productId、3 IsApproved[标志1/0]。一个产品可以有多个图像 我们有一个存储过程,它必须返回特定productId的所有已批准映像+该productId的所有已批准/未批准映像的计数 select * from images where isApproved=1 where productId = {user_entered_id}; select count(*) from images where pro

我们有一个包含以下列的images表:-1 imageId、2 productId、3 IsApproved[标志1/0]。一个产品可以有多个图像

我们有一个存储过程,它必须返回特定productId的所有已批准映像+该productId的所有已批准/未批准映像的计数

select * from images where isApproved=1
where productId = {user_entered_id};

select count(*) from images
where productId = {user_entered_id};
有没有更好的方法可以在一次查询中从images表中获取这2个信息?这是一个巨大的表,我们希望尽可能减少SQL查询


一种解决方法是-修改query1并将所有图像返回到应用程序服务器,并在其中筛选isApproved=1图像,但它将isApproved=0图像返回到应用程序服务器,这是不必要的,也是有风险的。有更好的方法吗?

有一种方法。但是,根据以产品id作为用户输入的实例数,计数将重复几次

SELECT imageId, count from
Images NATURAL JOIN
(SELECT productId, count(*) as count from images where isApproved=1 
GROUP BY productId 
HAVING productId = <user_input>)
WHERE productId = <user_input>;
但是,可以跳过GROUPBY子句。
希望这能有所帮助。

您可以聚合以下值:

select group_concat(case when isApproved = 1 then image_id end) as approved_image_ids,
       count(*) as num_images
from images i
where productId = {user_entered_id};
可能选择count*作为总计,sumisApproved作为productId=id的图像中的approved?