[英]request SQL 2 Left outer join
i tried to create a request with double LETF OUTER JOIN with sequelize without success i have 2 table : Users 我试图用双LETF OUTER JOIN创建一个带有续集的请求,但没有成功,我有2个表:Users
And : friends 和朋友
my userid and idfriend are related to my table user 我的userid和idfriend与我的表用户相关
if i have on my table user Id = X , userId = 23 , idFriend = 34 ,... 如果我在表上有用户ID = X,userId = 23,idFriend = 34,...
i have a query who provide me all row who have for example 23 (userID or Idfriend) how can i get the all the data of userId (username, email ...) and all the data idFriend(username, email ...) in the same request 我有一个查询,向我提供所有具有例如23(userID或Idfriend)的行,我如何获取userId的所有数据(用户名,电子邮件...)和所有数据idFriend(用户名,电子邮件...)在同一请求中
thx 谢谢
you should left join the user two time eg: 您应该两次离开用户,例如:
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
If I understand you right, you are trying to get data for userId and friendId with one query? 如果我理解正确,那么您正在尝试通过一个查询获取userId和friendId的数据吗? I think this must work for you, but you need to test it
我认为这必须对您有用,但是您需要对其进行测试
First way: 第一种方式:
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
Second way using UNION: 使用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)
Another way (this way have risk to return you empty if WHERE clause is null): 另一种方法(如果WHERE子句为null,则冒着返回空的风险):
SELECT user.*, friend.* FROM users as user
JOIN users as friend ON friend.id=34
WHERE user.id=23
I hope this will help you 我希望这能帮到您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.