多个连接的SUM记录错误

时间:2019-04-18 07:54:37

标签: mysql

我有3个表requestplanlevel

这是表格请求:

 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个表并计入表请求中,有多少条记录具有response_code 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

,它正确求和。如何优化查询?请帮助我

1 个答案:

答案 0 :(得分:1)

如果您要确定请求总数,那么COUNT()SUM()更好。

SELECT COUNT(*), response_code FROM requests
GROUP BY response_code

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