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

Combine Three mySQL queries into one and return one JSON object

我有这三个问题:

$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.

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

试试这个查询:

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