简体   繁体   English

PHP:从MySQL选择多个count(id)作为一个查询

[英]PHP : select multiple count(id) from MySQL as one query

I need to optimize the following code in one query : 我需要在一个查询中优化以下代码:

        $query = 'select count(id) as featured_ads from #___properties  WHERE featured = 1 and approved =1';
    $db->setQuery($query);
    $featured_ads = intval($db->loadResult());


    $query = 'select count(id) as wait_ads from #___properties  WHERE approved =0 and canceled<>"1" ';
    $db->setQuery($query);
    $wait_ads = intval($db->loadResult());


    $query = 'select count(id) as total_users from #__sresuad WHERE gid = 18 ';
    $db->setQuery($query);
    $total_users = intval($db->loadResult());

What should I do? 我该怎么办?

You want all the counts to be returned in one query? 您想在一次查询中返回所有计数吗? A simple way to address this is to just have all your SELECTs define fields for an outer SELECT: 解决此问题的一种简单方法是让所有SELECT都为外部SELECT定义字段:

SELECT
    (select count(id) from #___properties  WHERE featured = 1 and approved =1) AS featured_ads,
    (select count(id) from #___properties  WHERE approved =0 and canceled<>"1") AS wait_ads,
    (select count(id) from #__sresuad WHERE gid = 18) AS total_users

As suggested by Lodder in his comment, writing SQL queries by hand is prone to errors and security lapses, so you might want to avoid it if possible. 正如Lodder在其评论中所建议的那样,手工编写SQL查询容易出错和降低安全性,因此,如果可能,您可能要避免这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM