SQL - 使用另一个表中的条件执行SELECT

时间:2016-04-05 23:53:48

标签: mysql sql database

我有四个表:usergameuser_games_joineduser_rating

用户可以为其他用户提供“评级”,但仅限于他们与该用户玩过游戏(即user_games_joined表包含同一游戏的每个用户的行)他们上次为该用户评分

我正在尝试构建一个SELECT语句,它将告诉我们当前是否允许用户为另一个特定用户提供评级。这是我到目前为止所做的:

SELECT COUNT(*)
FROM user_games_joined from_joined
LEFT JOIN game ON from_joined.game_uuid = game.uuid
INNER JOIN user_games_joined to_joined ON from_joined.game_uuid = to_joined.game_uuid
WHERE from_joined.user_uuid = [USER_GIVING_RATING_UUID]
AND to_joined.user_uuid = [USER_RECEIVING_RATING_UUID]
AND game.date > [DATE_OF_MOST_RECENT_RATING];

如果此语句返回0,则最终答案为 false ;否则 true (自上次评级以来,两个用户之间至少玩过一个游戏)。问题是[DATE_OF_MOST_RECENT_RATING]未知:必须从user_rating表中确定。以下是我们如何查询该信息:

SELECT date from user_rating
WHERE to_user_uuid = [USER_RECEIVING_RATING_UUID]
AND from_user_uuid = [USER_GIVING_RATING_UUID]
ORDER BY date DESC LIMIT 1;

当然,我可以通过两个单独的查询完成此任务,但出于显而易见的原因,我想将它组合成一个语句。有人可以帮我解决这个问题吗?谢谢!

编辑:对于奖励积分,有人可以在插入user_rating表的过程中提出执行此检查的方法,因此无需进行验证在INSERT之前作为单独的查询?

2 个答案:

答案 0 :(得分:0)

这是一组相当复杂的连接,有一些聚合:

select (case when coalesce(max(ur.rating_date), max(g.date)) <= max(g.date) then 'Go and Rate'
             else 'No, no, no.  Go and play'
        end)
from user_game g join
     user_games_joined ufrom 
     on ufrom.game_uuid = g.uuid and
        ufrom.user_uuid = g.from_user_uuid join
     user_games_joined uto
     on uto.game_uuid = g.uuid and
        uto.user_uuid = g.to_user_uuid left join
     user_rating ur join
     on ur.from_user_uuid = ufrom.user_uuid and
        ur.to_user_uuid = uto.user_uid
where to_user_uuid = [USER_RECEIVING_RATING_UUID] and
      from_user_uuid = [USER_GIVING_RATING_UUID];

出于您的目的,更好的select是:

select (max(ur.rating_date) < max(g.date))

答案 1 :(得分:0)

编写通用查询,因为我不知道您正在使用哪个数据库。我没有测试过这个可能有一些错误,但你应该从下面得到它的要点。您可能需要调整查询的语法和性能:

connection = MySQLdb.connect()
cursor = connection.cursor()
cursor.execute("select * from table;")