我有3个表request
,plan
,level
。
这是表格请求:
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
,它正确求和。如何优化查询?请帮助我
答案 0 :(得分:1)
如果您要确定请求总数,那么COUNT()
比SUM()
更好。
SELECT COUNT(*), response_code FROM requests
GROUP BY response_code
您为什么要加入计划和价格?您需要从这些表中返回一些数据吗?