MySQL获得子查询值

时间:2013-02-28 11:29:52

标签: mysql

我正在尝试计算我的质心点的距离,这是通过标签的总数计算的,以及标签出现的即时时间的总和。这就是(tc_sum / cnt)的概念 然而,子查询上的SELECT,不允许我得到质心点,因为“centr”尚未计算,因此我无法得到“距离”。
有什么帮助吗?

SELECT cnt, tc_sum, ROUND(tc_sum/cnt) as centr, distance
FROM (
    SELECT SUM(timecode) as tc_sum, count(timecode) as cnt, ABS( centr - '".$timecode."' ) AS distance
    FROM dados d
    WHERE tag = 'donald'
    AND filename = 'donald.mp4'
    AND group_id = '1'
    ) d

2 个答案:

答案 0 :(得分:1)

尝试

SELECT cnt, tc_sum, ROUND(tc_sum/cnt) as centr, distance
FROM (
SELECT SUM(timecode) as tc_sum, count(timecode) as cnt, ABS( ROUND(tc_sum/cnt)- '".$timecode."' ) AS  distance
FROM dados d
WHERE tag = 'donald'
AND filename = 'donald.mp4'
AND group_id = '1'
) d

答案 1 :(得分:1)

SELECT 
 SUM(timecode) as tc_sum, 
 SUM(timecode) as cnt, 
 ABS( SUM(timecode) / SUM(timecode) - '".$timecode."' ) AS distance, 
 ROUND(SUM(timecode) / SUM(timecode)) AS centr
FROM dados d
WHERE tag = 'donald'
 AND filename = 'donald.mp4'
 AND group_id = '1'

查询一行一行,您不能以这种方式引用别名。你必须再次“重新计算”它们。 “重新计算”不是正确的词,因为结果并没有真正计算多次。优化器将负责仅计算一次。但只有查询运行后才能知道别名。我担心我的英语太糟糕了,无法以一种好的方式解释它:)