0

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.

  • You should add expected result from the query – Lennart May 17 '18 at 16:32
0

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.