选择字符并与连接组合在一起?

时间:2013-01-25 04:14:39

标签: mysql sql

我在mysql中设置了以下表格:

CREATE TABLE `games_characters` (
  `game_id` int(11) DEFAULT NULL,
  `player_id` int(11) DEFAULT NULL,
  `character_id` int(11) DEFAULT NULL,
  KEY `game_id_key` (`game_id`),
  KEY `character_id_key` (`character_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我的目标是获得一个game_id,其中一个character_id列表都出现在这个game_id中。

一组示例数据:

1, 1
1, 2
1, 3
2, 1
2, 2
3, 1
3, 4

假设我想获得game_id,其中character_id有1,2和3.我将如何进行高效查询?我到目前为止最好的想法是多次加入表格,但我认为必须有更好的方法来做到这一点。

由于

编辑:对于任何好奇的人来说,这是我使用的最终解决方案,因为它证明了最佳查询时间:

SELECT game_ID
FROM (
    SELECT DISTINCT character_ID, game_ID
    FROM games_Characters
) AS T
WHERE character_ID
IN ( 1, 2, 3 ) 
GROUP BY game_ID
HAVING COUNT( * ) =3

2 个答案:

答案 0 :(得分:4)

Select game_ID from games_Characters
where character_ID in (1,2,3)
group by game_ID
having count(*) = 3

the above makes two assumptions
1) you know the characters your looking for
2) game_ID and character_ID are unique

我不认为你知道你正在寻找的人名单,你可以得到#3,因为你知道你要找的人名单。

答案 1 :(得分:2)

应该这样做。

select game_id
from games_characters
where character_id in (1,2,3)
group by game_id
having count(*) = 3

如果这对你来说不够动态,你需要再添加一些步骤。

create temporary table character_ids(id int primary key);

insert into character_ids values (1),(2),(3);

select @count := count(*)
from character_ids;

select gc.game_id
from games_characters as gc
join character_ids as c
    on (gc.character_id = c.id)
group by gc.game_id
having count(*) = @count;