简体   繁体   English

TSQL / PHP太慢-重写

[英]TSQL / PHP Too Slow - Rewrite

I have a table called mainevents, and a table called subevents. 我有一个名为mainevents的表和一个名为subevents的表。 For each mainevent there are 3 subevents that I want, which match subname='$sub_name' and eventid. 对于每个主要事件,我需要3个子事件,它们与subname ='$ sub_name'和eventid相匹配。 When there are a lot of mainevents, the script is too slow. 当有很多主要事件时,脚本太慢。 Dragging slow, 10 seconds to load. 缓慢拖曳,需要10秒才能载入。 When I disable subevents loop, the script loads instantly. 当我禁用子事件循环时,脚本会立即加载。 I think there might be a shorter/faster/easier way of writing the following. 我认为可能会有更短/更快/更容易的方式编写以下内容。 Maybe all in one query. 也许全部在一个查询中。 I'm not completely sure. 我不太确定。

$a=sqlsrv_query($conn, "SELECT
    eventid,status,name, CONVERT(varchar(100),date,107) AS dt 
    FROM dbo.mainevents WHERE 
    ( date >= '$start_date' AND date <= '$stop_date' ) AND disabled='0'
    ORDER BY category asc");
while($e=sqlsrv_fetch_array($a)){
    $b=sqlsrv_query($conn, "SELECT 
        subid, subname FROM dbo.subevents WHERE
        eventid='$e[eventid]' AND subname='$sub_name' ORDER BY subname");
    while($s=sqlsrv_fetch_array($b)){
        //do stuff
    }
}

Why not join the two tables in the first query? 为什么不在第一个查询中联接两个表?

Where there are no sub events though you will need to put in an outer join or you will not get the main event. 没有子事件的地方,尽管您将需要进行外部联接,否则将不会获得主事件。

Let the SQL server's optimiser decide what needs looping. 让SQL Server的优化程序确定需要循环的内容。

The SQL would be something like this: SQL将是这样的:

SELECT m.eventid, m.status, m.name, CONVERT(varchar(100),date,107) AS m.dt, s.subid, s.subname 
FROM dbo.mainevents m, dbo.subevents s
WHERE m.eventId *= s.eventId
AND ( m.date >= '$start_date' AND m.date <= '$stop_date' ) 
AND m.disabled='0'
ORDER BY m.category asc, s.subname asc

I think that is the correct syntax for an outer join in T-SQL, but it is a long while since I did any T-SQL work! 我认为这是T-SQL中外部联接的正确语法,但是距离我进行任何T-SQL工作已经有很长时间了! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM