Reputation: 445
trying to save a step and combine these two queries but not sure how to go about it best. Basically the first query is getting the list of reviews in our system and the second one is seeing if a notification has been sent (if there are results returned then it has been sent).
get reviews:
SELECT r.*,
coalesce( ( SELECT AVG(rr.rating)
FROM `" . DBTABLEPREFIX . "reviews_ratings` rr
WHERE rr.review_id = r.id
)
, ''
) AS rating,
FROM `" . DBTABLEPREFIX . "reviews` r
WHERE BELOW SELECT IS 0 RESULTS
check if notification exists (yes I know this doesn't work by itself):
SELECT rn.*
FROM `" . DBTABLEPREFIX . "reviews_notifications` rn
WHERE rn.website_id = r.website_id
AND rn.post_id = r.post_id
Any ideas on the way to do this properly? Also in case you are wondering why we can't check r.id on the notifications table its because the reviews and reviews_ratings table are cleared each day with fresh data. The process will probably be rewritten later to not kill but only add new items.
Upvotes: 2
Views: 120
Reputation: 115530
You can use a correlated subquery, using NOT EXISTS
:
SELECT r.*,
coalesce( ( SELECT AVG(rr.rating)
FROM `" . DBTABLEPREFIX . "reviews_ratings` rr
WHERE rr.review_id = r.id
)
, ''
) AS rating,
FROM `" . DBTABLEPREFIX . "reviews` r
WHERE NOT EXISTS
( SELECT rn.*
FROM `" . DBTABLEPREFIX . "reviews_notifications` rn
WHERE rn.website_id = r.website_id
AND rn.post_id = r.post_id
)
The other subquery can be moved into the FROM
part:
SELECT
r.*,
coalesce( rr.rating, '' ) AS rating,
FROM `" . DBTABLEPREFIX . "reviews` r
LEFT JOIN
( SELECT
rr.review_id,
AVG(rr.rating) AS rating
FROM `" . DBTABLEPREFIX . "reviews_ratings` rr
GROUP BY rr.review_id
) AS rr
ON rr.review_id = r.id
WHERE NOT EXISTS
( SELECT rn.*
FROM `" . DBTABLEPREFIX . "reviews_notifications` rn
WHERE rn.website_id = r.website_id
AND rn.post_id = r.post_id
)
Upvotes: 1