Forum Moderators: open

Message Too Old, No Replies

Simplifying a table with both a JOIN and a NOT EXISTS (SELECT .)

         

csdude55

6:29 am on Apr 24, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



My original query joined one table for "favorites" and then did a "NOT EXISTS" for another table for "hide", but now I'm combining "favorites" and "hide" to a single table with an "action" column to determine whether it's a favorite or hidden.

In this query, I'm showing the logged-in user's favorites (as marked by "fave" in "action_list.action"), but also excluding IDs that are marked as "hide"; meaning, someone could mark, say, "NickMNS" as a favorite, then hide one of his ads, and still have all of Nick's other IDs in their favorite list. Alternatively, they could mark an ID as a favorite, then hide the username that posted that ID, and still have that ID show in their favorite list.

It's also entirely possible that the logged-in user's username will not exist in "action_list", in which case there will simply be 0 results.

Here's my original code, minus a bit of unnecessary stuff that just made it harder to decipher:

SELECT id FROM table
JOIN action_list
ON
action_list.username = 'csdude' AND
action_list.action = 'fave' AND
(
table.username = action_list.target_user OR
table.id = action_list.target_id
)
WHERE
NOT EXISTS
(
SELECT 1 FROM action_list
WHERE
action_list.username = 'csdude' AND
action = 'hide' AND
(
table.username = target_user OR
table.id = target_id
)
)
ORDER BY id DESC


I feel like there has to be a way to modify the "action_list ON" conditions and eliminate the NOT EXISTS, but everything I've tried has the wrong results.

Any suggestions?

JKumar

1:28 am on May 14, 2020 (gmt 0)

5+ Year Member



What is the new table structure of this action_list table?