Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

slow query help 1

Status
Not open for further replies.

thompom

Technical User
Dec 4, 2006
395
GB
Hi,

the query below counts records where typeid = 1 and where a record with a typeid = 2 does not exist - but runs slow

can anyone see a way to improve this?

Code:
SELECT event.eventid, 
event.deptlinkid, 
cus.custitle, 
cus.firstname, 
cus.surname, 
TA.actiondate 
FROM event 
INNER JOIN cus ON cus.cusid = event.cusid 

LEFT JOIN 
(SELECT action.actiondate, 
action.eventid 
FROM action 
WHERE action.typeid = '1' 
AND action.eventid NOT IN 

(SELECT action.eventid 
FROM action 
WHERE action.typeid = '2') 

)AS TA ON event.eventid = TA.eventid 

WHERE event.userid = '39' 
AND month(TA.actiondate) = '1' 
AND year(TA.actiondate) = '2010' 
GROUP BY event.eventid 
ORDER BY TA.actiondate DESC
 
Can you tell us what you are trying to accomplish? that may help us understand the query better.

+++ Despite being wrong in every important aspect, that is a very good analogy +++
Hex (in Darwin's Watch)
 
Hi,

apologies the query doesnt count! - it should show records from table event where a record in table action with a typeid of '1' exists BUT a record in table action with a typeid of '2' does not exist.
table action is linked to table event by action.eventid

hope this makes sense - have simplified the query below

Code:
SELECT event.eventid
FROM event 

LEFT JOIN 
(SELECT action.eventid 
FROM action 
WHERE action.typeid = '1' 
AND action.eventid NOT IN 

(SELECT action.eventid 
FROM action 
WHERE action.typeid = '2') 

)AS TA ON event.eventid = TA.eventid 

GROUP BY event.eventid
 
Code:
SELECT event.eventid
  FROM event 
LEFT OUTER
  JOIN ( SELECT eventid 
           FROM action 
         GROUP
             BY eventid
         HAVING COUNT(CASE WHEN typeid = '1'
                           THEN 'count me' END) > 0
            AND COUNT(CASE WHEN typeid = '2'
                           THEN 'no, me!!' END) = 0
       ) AS TA 
    ON TA.eventid = event.eventid
:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top