使用子查询优化MySQL查询

时间:2014-01-17 04:42:25

标签: php mysql sql

我正在尝试优化此查询以使其更有效并停止加载缓慢。有人可以告诉我我需要做些什么来优化这个以供将来参考。

SELECT * , username AS user, 
(SELECT COUNT(*) FROM pvp WHERE killer = user) AS kills, 
(SELECT COUNT(*) FROM pvp WHERE username = user) AS deaths, 
ROUND(kills / deaths, 2) AS kd FROM stats WHERE username =  "Username"

2 个答案:

答案 0 :(得分:1)

select *,pvptable.username As user,COUNT(pvptable.killer) as kills,
COUNT(pvptable.username) as deaths,
ROUND(COUNT(pvptable.killer) / COUNT(pvptable.username), 2) AS kd FROM stats as st
LEFT JOIN pvp as pvptable ON pvptable.killer='user' 
AND pvptable.username='user' WHERE st.username="Username";

答案 1 :(得分:0)

试试这个,

SELECT username AS user, sum(kills) kills,sum(deaths) deaths FROM    
(
 select (SELECT CASE WHEN killer = user THEN 1 ELSE 0 END kills,
  CASE WHEN username = user THEN 1 ELSE 0 END deaths from pvp),
  ROUND(kills / deaths, 2) AS kd FROM stats 
) a
GROUP BY username