Question : need help! exists subqueries are killing mysql server in production environment

I have this query that is totally jacked. Basically what it is trying to do, is sort of like a forum. There are notes which have threads. The threads are determined by topic_id or patient_id. This query goes and grabs all the "threads" for which the existing user participated. So that doesn't mean they started the thread, it just means that they had responded to a thread.

ALL Thread starter messages have a topic_id = '' and the messages in that thread have a topic_id = id of the thread starter message OR they have the same patient_id as the thread starter message

In the example below, the query is searching for thread starters only where the user has either created the thread or responded to the thread, or responded to the same patient as the thread.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
select portal_notes.topic_id, portal_notes.id, portal_users.first_name, portal_users.last_name, message, portal_notes.date_created, portal_notes.patient_id, portal_notes.subject, portal_notes.patient_reference from portal_notes 
LEFT JOIN portal_users ON portal_users.id = portal_notes.user_id 
where topic_id = ''
and portal_notes.subdomain_id = '4'
 
and (user_id = '43' # user can see conversations they have created
							
# user can see conversations they have participated in							
or exists(select * from portal_notes as notes2 where portal_notes.patient_id = notes2.patient_id and user_id = '43' )
or exists(select * from portal_notes as notes2 where portal_notes.topic_id = notes2.id and notes2.user_id = '43')
 
)
 
# sort by newest topic
	order by  (SELECT date_created
	FROM portal_notes portal_notes2
	WHERE portal_notes2.topic_id = portal_notes.id
	OR portal_notes2.id = portal_notes.id
	ORDER BY portal_notes2.date_created DESC
	LIMIT 1) desc

Answer : need help! exists subqueries are killing mysql server in production environment

replace select * for select 1 in the exists query.

or exists(select 1 from portal_notes as notes2 where portal_notes.topic_id = notes2.id and notes2.user_id = '43')  

Also make sure you have created indexes on columns subdomain_id, user_id, patient_id, topic_id and id.

Random Solutions  
 
programming4us programming4us