2

我有一个已简化并写在下面的查询。如何显示作为 2 个单独的内联选择语句计算的 2 个字段的时间差?

SELECT x.name ,
   ( SELECT data.ts 
     FROM data 
     WHERE prim_key = x.prim_key and roll_no ='1'  
 ) **starttime** ,
  ( SELECT data.ts 
    FROM woman_data 
    WHERE prim_key = x.prim_key and roll_no ='10'

) **endtime**
, **TIME_TO_SEC( TIMEDIFF( endtime , starttime)** as timediff // This line does not work.It cannot recognize endtime ans starttime
FROM data x 
     INNER JOIN  y 
ON x.prim_key = y.prim_key
ORDER BY x.prim_key
4

2 回答 2

0

将查询更改为“外层”的最简单方法:

SELECT
name,
starttime,
endtime,
TIME_TO_SEC( TIMEDIFF( endtime , starttime)) as timediff
FROM(
 SELECT
 x.prim_key,
 x.name ,
   ( SELECT data.ts 
     FROM data 
     WHERE prim_key = x.prim_key and roll_no ='1'  
 ) starttime ,
  ( SELECT data.ts 
    FROM woman_data 
    WHERE prim_key = x.prim_key and roll_no ='10'

) endtime

FROM data x 
     INNER JOIN  y 
ON x.prim_key = y.prim_key
) n
ORDER BY n.prim_key
于 2012-09-10T09:22:02.507 回答
0

试试这个:

starttime 和 endtime 是派生列,您不能在同一个 select 语句中使用它。您必须创建派生表,然后在外部查询中使用这些列

select name,starttime,endtime,TIME_TO_SEC( TIMEDIFF( endtime , starttime) as timediff
from(
SELECT x.name ,
   ( SELECT data.ts 
     FROM data 
     WHERE prim_key = x.prim_key and roll_no ='1'  
 ) starttime ,
  ( SELECT data.ts 
    FROM woman_data 
    WHERE prim_key = x.prim_key and roll_no ='10'

) endtime

FROM data x 
     INNER JOIN  y 
ON x.prim_key = y.prim_key)a
ORDER BY x.prim_key
于 2012-09-10T09:24:40.773 回答