Mysql 多重联接的总和记录错误

Mysql 多重联接的总和记录错误,mysql,Mysql,我有3个表请求,计划,级别 以下是表格请求: id plan_id response_code client_id 1 1 200 1 2 1 200 1 3 1 400 1 4 1 500 1 以下是表格计划: id client_id 1 1 2

我有3个表
请求
计划
级别

以下是表格请求:

 id  plan_id response_code client_id
  1  1        200           1          
  2  1        200           1
  3  1        400           1
  4  1        500           1
以下是表格计划:

 id       client_id
  1             1         
  2             1
  3             1
  4             1
以下是价格表:

     id  plan_id
      1  1               
      2  2       
      3  3       
      4  4     
我想加入3个表并在表请求中计数,有多少条记录的响应代码为200、400和500。但我得到了错误的值。这是我的问题

        SELECT 
      requests.id,
      SELECT SUM(case 
      when requests.response_code = 200 then 
      1 else 0
       end) as resquest200,
      SELECT SUM(case 
      when requests.response_code = 500 then 
      1 else 0
       end) as resquest500,
      response_code,
    FROM requests
    JOIN plan
    ON requests.plan_id = plan.id
    JOIN price
    ON plan.id = price.plan_id
    GROUP BY request.id
我试过:

 SELECT 
 request.id,
 (
SELECT SUM(case 
when request.response_code = 200 then 
1 else 0
end) FROM request) as resquest200,
response_code,
FROM request
JOIN plan
ON requests.plan_id = plan.id
JOIN price
ON plan.id = price.plan_id
GROUP BY request.id

它的总和是正确的。如何优化我的查询?请帮助我

如果您希望确定请求总数,那么
COUNT()
是比
SUM()更好的选择


你为什么想加入计划和价格?您需要从这些表中返回一些数据吗?

您期望的结果是什么?@D-Shih我期望:
response200:…,response400:,响应500:…..
@Akashii根据您的数据表示和第一次查询。计划表中没有“计划id”列,该列出现在您对plan.plan\u id=price.plan的查询联接价格中_id@RahulSinghsry,它是
plan.id=price.plan\u id
我正在查找每个响应代码请求的总数。示例:
response200:10,response400:20,response500:30
我认为这不需要来自计划或价格表的任何数据?请求表似乎包含返回此级别信息所需的所有内容。是的,我需要两个表中的数据,但我不包括在示例中。可能值得包含一个要返回的数据示例。如果您是按响应代码分组的,那么很难看到如何聚合价格表和计划表中的数据
SELECT COUNT(*), response_code FROM requests
GROUP BY response_code