Question

I am having trouble to find the best solution for the following problem;

Description: I want to select all records from an items table, unless it is for favorites only, in that case the user must be present in the owners favorites.

The tables look something like these;

Items table (Table that holds all the items)

+----+----------+---------------+
| id | owner_id | favorite_only |
+----+----------+---------------+
|  1 |        1 |             0 |
|  2 |        2 |             1 |
|  3 |        2 |             1 |
+----+----------+---------------+

Favorites table (Table which holds the owners favorite users)

+----+----------+---------+
| id | owner_id | user_id |
+----+----------+---------+
|  1 |        2 |       1 |
+----+----------+---------+

I hope the above sufficient, if not, please let me know.

Was it helpful?

Solution

I made a simple solution to my problem with the following condition;

CASE 
    WHEN items.favorite_only = 1 THEN 
    (SELECT favorites.user_id FROM favorites WHERE favorites.owner_id = items.owner_id AND favorites.user_id = 1 LIMIT 1)
    WHEN items.favorite_only = 0 THEN 1
END

Is there performance wise a better solution?

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top