简体   繁体   English

需要找到一个查询以在MySQL中返回某些结果

[英]Need to find a query to return a certain results in MySQL

I have two tables, User and relationshp. 我有两个表,User和Relationshiphp。 I need to find all the users who have sent the logged in user a friend request. 我需要找到已向登录用户发送好友请求的所有用户。

User Table                        relationship Table
------------         ----------------------------------------------
id | username         user_one_id | user_two_id | status | action_user_id

Those are my two tables. 那是我的两张桌子。 user_one_id is the user who sent the request, while user_two_id is the recipient. user_one_id是发送请求的用户,而user_two_id是收件人。

I need to find a query that will return all friend request received by the logged in user. 我需要找到一个查询,该查询将返回登录用户收到的所有朋友请求。

If tried the following, but it only returned only the name of the user logged in and the id of the users who sent them the request. 如果尝试以下操作,但仅返回登录用户的名称和向其发送请求的用户的ID。 Did not return the names of the sender. 没有返回发件人的名字。

 var loggedInUser = req.user[0];
 connection.query("
 SELECT User.id, User.username, relationship.user_one_id, 
 relationship.status 
 FROM User INNER JOIN relationship ON User.id=relationship.user_one_id 
 WHERE User.id = ?",
 [loggedInUser], function(err, results, fields) {}

Any help would be greatly appreciated. 任何帮助将不胜感激。

You would need to use two INNER JOIN statements in your query, one for user_one_id and another for user_two_id : 您将需要在查询中使用两个INNER JOIN语句,一个用于user_one_id ,另一个用于user_two_id

SELECT userA.id, userA.username, userB.id, userB.username, status, action_user_id
FROM relationship
INNER JOIN User AS userA ON userA.id = relationship.user_one_id
INNER JOIN User AS userB ON userB.id = relationship.user_two_id
WHERE userA.id = ?

UPDATED ANSWER: 更新的答案:

See link here for more details: http://sqlfiddle.com/#!9/af7ce/5 有关更多详细信息,请参见此处的链接: http : //sqlfiddle.com/#!9/af7ce/5

SELECT userA.id AS userA_id, userA.username AS userA_username, userB.id AS userB_id, userB.username AS userB_username, status, action_user_id, userC.username AS action_user_username
FROM relationship
INNER JOIN User AS userA ON userA.id = relationship.user_one_id
INNER JOIN User AS userB ON userB.id = relationship.user_two_id
INNER JOIN User AS userC ON userC.id = relationship.action_user_id
WHERE (userA.id = 1 OR userB.id = 1) AND userC.id != 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM