如何在mysql中选择具有多列值等于一组特定值的记录?

时间:2018-12-17 13:53:54

标签: mysql sql select

我有两个桌子

games

idGame  guidUser  
-----------------
12       2        
13       3


wordstyped

idGame  guidUser  word
-------------------------
12       2        honey
12       2        apples
13       3        bread
13       3        water
14       4        foo
15       5        bar
16       2        bartender
12       4        bar

我想选择游戏中包含情侣(idGame,guidUser)的单词类型的记录。

如果要搜索的值只有我可以做到的

SELECT * FROM wordstyped WHERE guidUser IN (SELECT guidUser from games)

但是如果要比较的值是几个值怎么办?

对于有效的查询,在此示例中,仅会选择单词类型的前4条记录。

4 个答案:

答案 0 :(得分:3)

这是联接解决方案:

SELECT w.idGame, w.guidUser, w.word
FROM wordstyped w
INNER JOIN games g
    ON w.idGame = g.idGame AND w.guidUser = g.guidUser;

enter image description here

Demo

答案 1 :(得分:2)

在MySQL中,您 可以 执行此操作:

SELECT *
FROM wordstyped
WHERE (idGame, guidUser) IN (
    SELECT idGame, guidUser
    FROM games
);

它将与子查询匹配idGame, guidUser对。但是,我建议您遵循以下标准:

SELECT *
FROM wordstyped
WHERE EXISTS (
    SELECT 1
    FROM games
    WHERE idGame = wordstyped.idGame AND guidUser = wordstyped.guidUser
);

答案 2 :(得分:1)

您可以使用内部联接并在JOIN条件下匹配多个字段

SELECT wordstyped.* FROM wordstyped 
INNER JOIN games ON 
         wordstyped.guidUser = games.guidUser 
         AND games.idGame = wordstyped.idGame

答案 3 :(得分:0)

这应该可以解决您的问题

SELECT * FROM wordstyped w
JOIN games g 
ON w.idGame=g.idGame
AND w.guidUser=g.guidUser