【问题标题】:request SQL 2 Left outer join请求 SQL 2 左外连接
【发布时间】:2018-04-20 18:47:45
【问题描述】:

我尝试使用双 LETF OUTER JOIN 创建一个请求,但没有成功 我有 2 个表:用户

还有:朋友

我的 userid 和 idfriend 与我的表用户相关

如果我的桌子上有用户 Id = X , userId = 23 , idFriend = 34 ,...

我有一个查询向我提供所有行,例如 23(userID 或 Idfriend) 如何在同一个请求中获取 userId (username, email ...) 的所有数据和所有数据 idFriend(username, email ...)

谢谢

【问题讨论】:

  • 我不懂数据库设计..为什么朋友表中需要3个id列(id、idfriend和userId)
  • @marius 你会建议我什么设计?
  • 对我来说,来自 Friend 表的 id 和 idFriend 似乎是同一件事,来自 Friend 表的 id。我不明白你为什么需要这两个字段。
  • Id 是关系 issuer 的 Id 与表 user 相关,Idfriend 也与 user 表相关
  • 对不起。我不明白..所以你有用户表 (row1: Id: 1, name='x', ...., row2: Id = 2, name = 'y'.. and table friends with row1: Id = 1,UserId = 2,从用户链接到 row2)。你有 userId 字段来链接朋友表和用户。

标签: javascript sql node.js sequelize.js


【解决方案1】:

你应该离开加入用户两次例如:

  select a.userId, a.Idfriend, b.username as  username, c.username as friendname 
  from  friends a
  left join user b on b.id = a.userId 
  left join user c on c.id = a.idfriend 

【讨论】:

  • 你知道怎么做吗?
【解决方案2】:

如果我理解正确,您是在尝试通过一次查询获取 userId 和friendId 的数据吗?我认为这一定对您有用,但您需要对其进行测试

第一种方式:

SELECT user.*, friend.* FROM users
LEFT JOIN users as user ON user.id=23
LEFT JOIN users as friend ON friend.id=34
LIMIT 1

使用UNION的第二种方式:

(SELECT user.*, friend.* FROM users as user
LEFT JOIN users as friend ON friend.id=23
WHERE user.id=34 OR user.id IS NULL)
UNION
(SELECT user.*, friend.* FROM users as user
RIGHT JOIN users as friend ON friend.id=34
WHERE user.id=23 OR user.id IS NULL)

另一种方式(如果 WHERE 子句为空,这种方式有可能将您返回为空):

SELECT user.*, friend.* FROM users as user
JOIN users as friend ON friend.id=34
WHERE user.id=23

希望对你有帮助

【讨论】:

  • 你知道我怎样才能用 sequelize 做到这一点
猜你喜欢
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多