开发者

How can I subtract the values in one row from the values in another row in the same mysql table

I have the following query in a php file:

$query = "SELECT 
    a.aurl as al,
    (a.lttotals 
       - 
       ( SELECT b.lttotals 
         FROM stats b 
         WHERE ltdate='$newdate'
         AND b.aurl=a.aurl
       )
    ) as tt,
    lttotals
 FROM stats a 
 WHERE ltdate='$date'
 ORDER BY lttotals DESC 
开发者_如何学JAVA LIMIT 20";

This is very slow and if I change the limit to more than 20 mysql goes away. ;)

Basically what I need to do is to take the values from certain columns in one row and subtract them from another row.

Is there a better way to do what I am trying to do using what I have now or should I restructure how I store my data?


SELECT  a.aurl AS a1,
        a.lttotals
        a.lttotals - b.lttotals
FROM    stats a
JOIN    stats b
ON      b.aurl = a.aurl
        AND b.ltdate = '$newdate'
WHERE   a.ltdate = '$date'
ORDER BY
        a.lttotals DESC
LIMIT 20

Create the following indexes:

stats (ltdate, lttotals)
stats (ltdate, aurl)

for this to work fast.


SELECT a.url AS al,
   (a.lttotals - b.lttotals) AS tt,
   a.lttotals
FROM stats a, stats b
WHERE a.ltdate='$date' AND b.ltdate='$newdate' AND a.url = b.url
ORDER BY a.lttotals DESC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜