【问题标题】:Joining table to other table using either one of two columns使用两列之一将表连接到另一个表
【发布时间】:2019-01-11 12:12:56
【问题描述】:

我目前正在用 C# 编写一个程序,我想根据作为函数参数传递的 id 从数据库中加载友谊。

我有 2 个表格(我只显示重要的列)。

表 1:玩家

+----------------------+---------------------+------+-----+---------+----------------+
| Field                | Type                | Null | Key | Default | Extra          |
+----------------------+---------------------+------+-----+---------+----------------+
| id                   | int(11)             | NO   | PRI | NULL    | auto_increment |
| username             | varchar(15)         | NO   |     | NULL    |                |
+----------------------+---------------------+------+-----+---------+----------------+

表 2:messenger_friends

+-------------+---------+------+-----+---------+-------+
| Field       | Type    | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| user_one_id | int(11) | NO   | PRI | NULL    |       |
| user_two_id | int(11) | NO   | PRI | NULL    |       |
+-------------+---------+------+-----+---------+-------+

问题是,我的想法如下:在 messenger_friends 中,为友谊保留一行。我知道我可以为一个友谊保存 2 个,但这意味着更多的存储空间,因为 500 个友谊将变成 1000 个记录。现在,在我的应用程序中,我必须将messenger_friends 加入到players。我得到了这个功能:

public async Task<IReadOnlyList<MessengerFriend>> GetFriends(int playerId)

在这里,我需要从messenger_friends 获取所有记录,其中user_one_iduser_two_idplayerId。然后在同一个查询中,我想将它加入到玩家中。我知道我可以通过这种方式获取记录:

SELECT * FROM messenger_friends WHERE user_one_id = {playerId} OR user_two_id = {playerId}

但我不确定如何将其加入players 表,因为我需要加入user_one_iduser_two_idplayers.id

【问题讨论】:

  • JOIN messenger_friends f ON p.id in (f.user_one_id, user_two_id)
  • JOIN table ON id IN (fk1, fk2) 是个好主意,我不知道它是否有效。顺便说一句,您应该将其发布为答案@juergend f.user_two_id
  • 您写的 这意味着更多的存储空间,因为 500 条友谊将变成 1000 条记录。相对而言,这是对数据进行去优化(非规范化)的一个不好的理由。如果您有选择,请不要使用额外的行来满足需要的额外列来设计您的数据。阅读规范化。
  • @O.Jones 所以你说将它存储为user_idfriend_id 而不是我想怎么做会更整洁/更好?
  • 是的,完全正确。这是一种更灵活的方法,而且正如您所发现的,它可以产生更简单、更清晰的查询。

标签: c# mysql join


【解决方案1】:
SELECT * 
FROM players p
JOIN messenger_friends f ON p.id in (f.user_one_id, f.user_two_id)
WHERE p.id = {playerId}

SELECT * 
FROM players p
JOIN messenger_friends f ON p.id = f.user_one_id
                         OR P.id = f.user_two_id
WHERE p.id = {playerId}

【讨论】:

  • 我看到你更新了你的答案,但这不起作用,因为= {playerId} 会将你自己的 ID 链接到玩家而不是你朋友的 ID。不过,我能够让它与!= 一起工作。
  • 感谢您的查询,我认为 OR 可能在 JOIN 中不起作用。 (无法编辑评论)。
猜你喜欢
  • 2023-03-19
  • 2020-06-23
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
相关资源
最近更新 更多