查询一对多对多表关系的最有效方法
我有 3 个描述游戏的 MySQL 表:
- gamelist {gameId, ... with Primary(gameId) } = 存储有关每个游戏会话的信息。
- userlist {userId, ... with Primary(userId) } = 存储每个用户的信息。
- game2user {gameId, userId ... with Primary(gameId, userId) } = 存储参与每个游戏会话的用户(一个游戏会话涉及两个或多个用户)。
现在,对于某个 userId,我需要检索一个游戏列表,其中包含该游戏会话中涉及的所有用户的名称。
到目前为止我得到的最好的结果是:
SELECT gl.gameid, gl.type, [...], ul.userid, ul.username
FROM userlist as ul, gamelist as gl, game2users as g2u
WHERE g2u.userid = a_certain_numeric_id AND
ul.userid = g2u.userid AND
gl.gameid = g2u.gameid`
这从游戏列表中检索唯一的行,但它只获取给定用户的用户名,而不是他的同事。
问题是如何在性能(时间)方面有效地做到这一点,并且最好不进行单独的查询?谢谢。
I have 3 MySQL tables that describe a game:
- gamelist {gameId, ... with Primary(gameId) } = Stores information about each game session.
- userlist {userId, ... with Primary(userId) } = Stores each user's information.
- game2user {gameId, userId ... with Primary(gameId, userId) } = Stores which users are involved in each game session (one game session to two or more users).
Now, for a certain userId, I need to retrieve a list of games that include the names of all the users involved in that game session.
The best I came out with so far is:
SELECT gl.gameid, gl.type, [...], ul.userid, ul.username
FROM userlist as ul, gamelist as gl, game2users as g2u
WHERE g2u.userid = a_certain_numeric_id AND
ul.userid = g2u.userid AND
gl.gameid = g2u.gameid`
This retrieves the unique rows from games list, but it only fetches the given user's username and not his co-players.
The question is how can I do this efficiently in terms of performance (time) and preferably without doing separate queries? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这本质上是查找给定用户参与的所有游戏(在子查询中),然后选择也参与该游戏的所有用户。
This essentially looks for all games where the given user is involved (in the subquery) and then selects all users that are also involved in that games.
试试这个:
Try this:
表和关系的完整架构将帮助我们为您提供帮助。
我不是 MySQL 专家,但似乎您使用不同的数据库实现可能会更好(如果您可以更改它)。现在 games2user 表中有冗余记录。我认为最简单的事情是为用户表提供一个包含他们参与的游戏的属性。然后,当您查询此问题时,您只需在 gamesTable 中查询用户参与的特定游戏并检索该游戏涉及的所有用户 ID。
The full schema for the tables and relationships would help us help you.
I'm not an expert on MySQL but it seems like you may be better off with a different implementation of the database (if you can change that). Right now you have redundant records in games2user table. I think the easiest thing would be to give the user table an attribute that contains the game they are involved in. Then when you do your query for this problem you can just query the gamesTable for the specific game that the user is involved in and retrieve all of the userIDs involved in that game.