문제

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.

도움이 되었습니까?

해결책

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 dba.stackexchange
scroll top