将三个mySQL查询合并为一个并返回一个JSON对象

时间:2015-02-27 13:29:22

标签: php mysql json pdo

我有这三个问题:

$sql = "select count(distinct f_home) as home_count_total from cr_test;" ;

$sql2 = "select distinct f_home, count(f_home) as home_count from cr_test group by f_home;" ;

//下面的伪代码

$sql3 = "select distinct f_home, round(count(f_home)/<home_count_total  FROM FIRST QUERY>*100,2) as CountOf from cr_test group by f_home;" ;

我需要的是一个json对象(我​​可以通过PDO获得,所以不要担心)每个条目有三个数据:f_home,home_count和CountOf。

如何将这些组合成一个查询,以便返回一个JSON对象?

1 个答案:

答案 0 :(得分:1)

尝试使用此查询:

SELECT 
  f_home, 
  COUNT(f_home) AS home_count,
  ROUND(COUNT(f_home) / home_count_total * 100, 2) AS CountOf
FROM 
  cr_test,
  (SELECT COUNT(DISTINCT f_home) AS home_count_total FROM cr_test) t
GROUP BY f_home