如何比较两个表并确定要返回的特定类型的行?

How to compare two tables and identify a specific type of row to be returned?

我有两个 table 数据相对不同。

photos table 是一个 table,包含照片的所有相关元数据,例如 user_id、photo_id、日期时间、名称等.

我还有另一个 table ratings 保存每张照片的 liked/disliked 数据。此 table 中的列将具有 rater_id(对图片进行评级的人)、photo_id 和评级 (like/dislike)。

用户会看到一张图片(随机),然后选择他们是否喜欢。每次图像 loaded/presented 都必须是他们尚未评级的图像。

我想做的是 return 一个 photo_id 用户还没有评价它的地方。

我考虑过使用连接或联合,但我很难理解如何将它们(或任何其他解决方案)最好地用于此应用程序。我的困惑在于如何将 ratings table 与 photos table 进行比较,仅 return 未被 [= 评级的照片17=].


示例数据

photos table

id | photo_id
-------------------------
1  | photo_123
2  | photo_456
3  | photo_432
4  | photo_642
-------------------------

ratings table

id | photo_id | rater_id | rating
---------------------------------
1 | photo_123 | user2 | 1
2 | photo_456 | user2 | 1
3 | photo_123 | user1 | 1
4 | photo_642 | user2 | 1
--------------------------------

示例结果:return photo_432 for user2 因为它在 ratings table

中还没有评级

规范的方式是 not exists:

select p.*
from photos p
where not exists (select 1
                  from ratings r
                  where r.photo_id = p.id and
                        r.rater_id = @rater
                 )
order by rand()
limit 1;

如果 table 很大,有更有效的方法来恢复随机行。