I have a post table that stores the most liked comment (top_comment).
I need an SQL statement that updates the top_comment when a comment is liked/unliked:
UPDATE post
SET top_comment = T1.body
FROM
(
SELECT body
FROM comment
WHERE count_like > 0
AND fk_post = 1
ORDER BY count_like DESC
LIMIT 1
) T1
WHERE pk_post = 1;
This works when there is a comment with likes however when no comments have likes I wish to update the top_comment to be NULL.
I’d prefer to do this as a single statement rather than two statements.
4
Answers
try this:
EDITED: Added new method to do this with one statement
BELOW WE UPDATE WITH JOIN TO ACHEIVE THE SOLUTION IN SINGLE STATEMENT
These are two suggestion you can do
Here you set your top comment value to NULL and then update it with new value if subquery returns any record.
**In the second suggestion you can check with IF EXIST **
You may use correlated subquery as a source of new value:
See db<>fiddle
You can use union all select ‘default value’ where not exists (select 1 from T1)
Something like this:
This is just to answer your question but it’s dirty why would you put the id yourself and call the update yourself, the best solution is to use triggers as in : https://stackoverflow.com/a/73538944/6150881