2013-04-10 70 views
0

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個請求對我來說似乎太重要了,這是處理這個問題的正常方法嗎?

+0

你想怎麼的結果是,會不會是一個單一的集合,或者您需要3個不同的集合 – 2013-04-10 02:53:07

+0

@ArunPJohny不知道你的收藏 – 0xSina 2013-04-10 03:05:33

+0

如果是什麼意思你需要3個不同的集合對象,那麼你需要執行所有三個查詢,如果你可以在一個集合中處理結果,那麼你可以使用下面給出的答案 – 2013-04-10 03:07:11

回答

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

+0

錯過了'games.status' – PinnyM 2013-04-10 02:59:28

+0

@PinnyM檢查,我在編輯代碼之間,是的,我確實懷念那個第一次,謝謝 – 2013-04-10 03:02:07

+0

「您的SQL語法錯誤;檢查對應於你的MySQL服務器版本的進步‘ 當games.status = 2那麼‘鰭’在第3行「 – 0xSina 2013-04-10 03:02:54

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列,以確定哪一行是哪個。

相關問題