从满足某些要求的表中获取数据

时间:2016-03-14 20:42:48

标签: mysql sql subquery logic

我陷入了SQL逻辑问题。 我有一个表“游戏”,其中包含一些数据,其中player1_id和player2_id是用户ID,它们在棋子匹配中相互玩耍:

每个游戏都以不同的环境开始,已在另一个表中指定(由“game_id”列键入)。 假设每个人都在线,用户无法重播同一个游戏。 如何只选择未播放我尚未播放的游戏的用户才能与我匹配? AJAX调用将匹配尚未玩特定游戏的两个用户并将其播放。 无论用户是player1还是player2,他都不能重复游戏。 非常感谢你。

表格:

game_match

+----+---------+------------+------------+
| id | game_id | player1_id | player2_id |
+----+---------+------------+------------+
|  1 |       1 |         16 |         17 |
|  2 |       1 |         18 |         23 |
|  3 |       1 |         19 |         21 |
|  4 |       1 |         20 |         22 |
|  5 |       2 |         20 |         17 |
|  6 |       2 |         16 |         18 |
|  7 |       2 |         19 |         23 |
|  8 |       1 |         25 |         15 |
+----+---------+------------+------------+

用户

+----+-----------+
| id | name      |
+----+-----------+
| 17 | Donald    |
| 18 | Margarida |
| 19 | Daisy     |
| 20 | Mickey    |
| 21 | Steve     |
| 22 | Raul      |
| 23 | Janis     |
| 24 | Michael   |
| 25 | Sergio    |
| 26 | Bill      |
| 27 | Alina     |
| 28 | Alana     |
| 29 | Harumi    |
| 30 | Danielle  |
| 31 | Lisa      |
+----+-----------+

谢谢!

3 个答案:

答案 0 :(得分:0)

假设您有一个名为Thread t = new Thread (() => threadRequest.clientInteraction(connection)); t.Start(ref teamInformation); games的表,您可以使用$userid轻松完成此操作:

not exists

请注意,您可以使用select g.* from games g where not exists (select 1 from game_match gm where gm.game_id = g.game_id and gm.player1_id = $userid ) or not exists (select 1 from game_match gm where gm.game_id = g.game_id and gm.player2_id = $userid ) ; 和一个子查询实现相同的逻辑。但是,使用正确的索引,两个子查询更有效。

答案 1 :(得分:0)

为了吸引用户,我会在子查询中使用union:

select * 
from users 
where id not in 
   (select player1_id as played
    from game_match 
    where player2_id = @logged_in_user
    union
    select player2_id 
    from game_match 
    where player1_id = @logged_in_user
    ) as played

答案 2 :(得分:0)

使用NOT EXISTS和INNER JOIN尝试以下解决方案:

select name
from Users AS u
where not exists(
    select 1 
    from game_match AS gm INNER JOIN
    (select distinct game_id 
     from game_match
     where @current_user_id = player1_id OR @current_user_id = player2_id) gids
        USING(game_id)
    where u.id = gm.player1_id OR u.id = gm.player2_id
    );