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

时间:2015-10-14 13:39:20

标签: php mysql select joomla

我需要在一个查询中优化以下代码:

        $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());

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您希望在一个查询中返回所有计数吗?解决这个问题的一个简单方法就是让所有SELECTs为外部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

正如Lodder在他的评论中所建议的那样,手工编写SQL查询容易出错和安全漏洞,所以如果可能的话你可能想避免它。