为什么查询无法使用mysqli选择特定ID?

时间:2019-02-05 13:02:16

标签: php mysql sql mysqli

我在使用mysqli表时遇到一个奇怪的问题。我有其中有一些记录的表。我正在执行以下查询

SELECT * FROM `users` WHERE 
EXISTS (
  SELECT * 
  FROM `games` 
  INNER JOIN `users_games` 
    ON `games`.`id` = `users_games`.`game_id`
  WHERE 
    `users`.`id` = `users_games`.`user_id` AND `game_id` = 10
  ) 
AND `users`.`id` = 10 
LIMIT 12;

users_games表中,有11的{​​{1}}行(1 to 13)。上面的查询适用于所有

user_id = 10

当我尝试执行`game_id` = 10 /* it is working */ 时,它没有显示记录,但是game_id= 1有一行。

game_id= 1表下方

enter image description here

1 个答案:

答案 0 :(得分:1)

给这些用户

select id from users;
+-----+
| id  |
+-----+
|   1 |
|   2 |
|   3 |
|   6 |
|   7 |
|   8 |
|  10 |
|  12 |
|  14 |
|  15 |
|  16 |
|  17 |
| 999 |
+-----+

还有这个

drop table if exists games,users_games;

create table games (id int);
create table users_games(user_id int, game_id int);

insert into games values (1),(10);
insert into users_games values(1,1),(1,10),(10,1);

您的查询

SELECT id FROM `users` WHERE 
EXISTS (
  SELECT * 
  FROM `games` 
  INNER JOIN `users_games` 
    ON `games`.`id` = `users_games`.`game_id`
  WHERE 
    `users`.`id` = `users_games`.`user_id` AND `game_id` = 1
  ) 
AND `users`.`id` = 10;

产生

+----+
| id |
+----+
| 10 |
+----+
1 row in set (0.00 sec)

符合预期。您可以通过将示例数据作为文本包含在问题中来改进您的问题(就像我在答案中所做的那样。)