0

I have the following tables (unrelated columns left out):

games:
id
 1
 2
 3
 4

bets:
id | user_id | game_id
 1 |    2    |   2
 2 |    1    |   3
 3 |    1    |   4
 4 |    2    |   4

users:
id
 1
 2

I have "games" on which "users" can place "bets". Every user can have a maximum of one bet on any single game but there can also be games where the user has no bet (user 1 has no bet on games 1 or 2 for example).

I now want to show a single user (let's say user with id 1) every game and his bet on this game (if he happens to have a bet on that game).

For the example above that would mean the following:

desired results:
game.id | bet.id
   1    |    null
   2    |    null
   3    |    2
   4    |    3    

To summarize:

There are games

  • that have no bet at all (game 1)
  • that have bets by users i don't care about right now (game 2)
  • that have bets by the user i care about AND

    • have no bets from other users (game 3)
    • also have bets from other users (game 4)

I've spend the whole afternoon trying to come up with a nice solution but i didn't so any help is appreciated.

If possible please don't use subqueries since these aren't really supported in the environment where i am going to use it.

Thanks!

4

3 回答 3

1

你试过这个吗?

SELECT  a.id GameID,
        b.id BetID
FROM    Games a
        LEFT JOIN bets b
            ON  a.id = b.game_id AND
                b.user_id = 1  -- <<== ID of the User
ORDER   BY a.ID ASC
于 2013-08-04T19:25:39.310 回答
1

您可以在以下条件下使用简单的左连接(假设用户 id = 1):

SELECT games.id, bets.id 
FROM games 
LEFT JOIN ON (bets.game_id = games.id AND bets.user_id = 1);
于 2013-08-04T19:25:40.263 回答
1

您必须使用 LEFT JOIN,但您还必须将用户的条件放入您的 JOIN 而不是 WHERE,否则将无法正常工作。

所以像这样:

SELECT g.id AS game_id, b.id AS bet_id 
FROM games g LEFT OUTER JOIN bets b ON g.id=b.game_id AND b.user_id = 1
于 2013-08-04T19:31:37.943 回答