编写最有效的查询(SQL)?

时间:2013-11-12 14:02:33

标签: sql database

我有一张表,我试图获取一些信息。  成功获取信息但速度很慢。  试图通过其他方式来做到这一点。  想知道你是否有一些想法。

我想要一个startdate和一个enddate。但是如果另一个标签名称在这些日期之间的最大值为10,我只想要它们。

我现在所做的就是写作。  这段代码有效但不是那么有效,因为它循环 通过各种可能性。

PLZ帮助

for (select ts as st from history  
    where name='tagg1' and value = '1' and ts between t0 and t1 and request='4')
    do

endDate=(select ts as en from history  where name='tagg2' and ts between st+25:00 and st+40:00 and request ='4' and 
    value='0');

totalsum = (select max from history1 where name='tagg3' and ts between st and endDate )

if totalsum = 10 then
  write st || endDate
end;

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
    T2.*
FROM
    history1 JOIN
    (
        select 
            T1.start,
            ts as end 
        from 
            history JOIN
            (
                select 
                    ts as start
                from 
                    history  
                where 
                    name = 'tagg1' and 
                    value = '1' and 
                    request = '4' and
                    ts between t0 and t1
            ) T1 ON (history.ts BETWEEN T1.start + 25:00 and T1.start + 40:00)
        where 
            name = 'tagg2' and 
            value = '0' and
            request = '4'
    ) T2 ON (history1.ts between start and end)
WHERE
    history1.name = 'tagg3' AND
    max = 10

此查询应仅返回由write st || endDate打印在脚本中的记录。