tags:

views:

38

answers:

1
select nid, avg, std from sView1
  where sid = 4891
    and nid in (select distinct nid from tblref where rid = 799)
    and oidin (select distinct oid from tblref where rid = 799)
    and anscount > 3

This is a query I'm currently trying to run. And running it like this takes about 3-4 seconds. However, if I replace the "4891" value with a subquery saying (select distinct sid from tblref where rid = 799) the procedure just hangs, even though the subquery only returns one sid.

The query is supposed to return a dataset with averages (avg) and standard deviations (std) over a resultset which is calculated through nested views in sView1. This dataset is then run through another view to get some top-level averages and stdevs.

The averages may need to include more than 1 sid (sid identifies a dataset).

It's difficult describing it more without revealing codebase and codestructure that shouldn't be revealed ;)

Can anyone suggest why the query hangs when trying to use the subquery? (The code is rebuilt from originally using nested cursors, since I have been told that cursors are the work of the devil, and nested cursors may make me sterile)

A: 

Try this. Exists returns as soon as it finds a matching condition, select distinct will require going through the dataset and optionally sorting it to remove the duplicates.

SELECT nid,avg,std from sView1 AS SV
WHERE EXISTS (SELECT * FROM TblRef AS TR WHERE sv.sid = Tr.sid AND Sv.nid = tr.nid AND sv.oid = tr.oid AND tr.rid = 799)
AND ansCount>3

Also, it is pretty difficult to provide a meaningful answer without access to query plans and table structures. So DDL and sample data will definitely help.

no_one
That isn't the same semantics as the original query. Your query enforces that the matching tr.oid, tr.nid and Tr.sid should all be from the same row.
Martin Smith
If you look at his original post - select distinct sid from .. , then the query does look semantically similar.
no_one
Similar, but not the same - as Martin observes, the original query did not mandate that nid and oid had to be on the same row on TblRef.
Mark Bannister
The OP should clarify what he is after.
no_one