I have two tables
requests - request_id, request_message, user_id
responses - response_id, request_id, response_message, user_id, status
I am running this query to get the count of unread responses, which belongs to a particular user.
SELECT COUNT(*)
FROM RESPONSES
WHERE status = 'U'
and request_id IN ( SELECT request_id FROM requests WHERE user_id = '$User_id')
Is there any way to optimize it using join??
I’d suggest using an explicit join instead of a subquery:
are the request_id fields indexed? I’m guessing it’s the PKEY in requests. What about the user_id field in requests?
Also, while I copied your syntax for it, I hope $User_id is not a variable being filled by user generated input. You should be using bind parameters (the method will depend on what language you are using.)