我必须两次查询才能得到这个结果吗?

时间:2013-04-10 02:50:49

标签: mysql sql

SQL新手。我有3个表:gamesinvitationsusers

此查询返回正在进行的游戏:

SELECT games.* 
FROM   games 
       INNER JOIN invitations 
               ON invitations.game_id = games.id 
                  AND invitations.user_id = 1 
                  AND invitations.status = 1 
                  AND games.status = 1; 

此查询返回已完成的游戏:

SELECT games.* 
FROM   games 
       INNER JOIN invitations 
               ON invitations.game_id = games.id 
                  AND invitations.user_id = 1 
                  AND invitations.status = 1 
                  AND games.status = 2; 

此查询返回用户尚未决定是否加入的游戏:

SELECT games.* 
FROM   games 
       INNER JOIN invitations 
               ON invitations.game_id = games.id 
                  AND invitations.user_id = 1 
                  AND invitations.status = 0;

我想知道,如果我有一个需要来自这3个查询的结果的Web应用程序,我是否必须执行3个sql语句或者有没有办法将它们压缩为1?提出3个请求对我来说似乎太过分了,这是解决这个问题的正常方法吗?

2 个答案:

答案 0 :(得分:1)

你可以这样压缩它:

SELECT games.*, 
       CASE WHEN invitations.status = 1 THEN games.status 
            ELSE invitations.status 
       END status 
FROM   games 
   INNER JOIN invitations 
   ON invitations.game_id = games.id 
      AND invitations.user_id = 1 
      AND ((invitations.status = 1 AND games.status IN (1,2))
         OR (invitations.status = 0))

您可以使用返回的status列来确定哪一行。

答案 1 :(得分:1)

试试这个

SELECT 
case when invitations.status = 1 
 then case 
        when games.status = 1 then 'progress'
        when games.status = 2 then 'finished'
      end
else 'not decided' end as game_status,
games.* 
FROM   games 
       INNER JOIN invitations 
               ON invitations.game_id = games.id 
                  AND invitations.user_id = 1 
                  AND (invitations.status = 0 or 
                        (invitations.status = 1 and games.status in (1,2)))

SQL DEMO