简体   繁体   English

使用 mysql JOIN 到 select 数据

[英]Using mysql JOIN to select data

I have two tables representing users and their friends: users and friendships我有两个代表用户及其朋友的表: usersfriendships

  • users has id and name usersidname
  • friendships has id , friend1_id and friend2_id friendshipsidfriend1_idfriend2_id

By searching a user's name, I want to get their associated friends' names.通过搜索用户的名字,我想得到他们相关朋友的名字。

You can try this:你可以试试这个:

SELECT u2.name from users u1
INNER JOIN users u2 ON u1.name = [your_name_to_search]
INNER JOIN friendships fs 
ON u2.id = fs.friend2_id AND u1.id = fs.friend1_id

Explanation :说明

I used 2 joins in this approach: the first users self join will assure you take the id corresponding to [your_name_to_search] , and then the second join with friendships will extract the names of friend_2_id matching with the friend_1_id taken from the first join.我在这种方法中使用了 2 个加入:第一个users自我加入将确保您获取对应于[your_name_to_search]id ,然后第二个加入friendships将提取与第一次加入中获取的friend_2_id匹配的friend_1_id的名称。

You can test this approach on this db-fiddle您可以在这个 db-fiddle 上测试这种方法

Join friendships to 2 copies of users .friendships加入 2 个users副本。
The 1st copy will be filtered for the user name that you search for and the 2nd will return all the user's friends:第一个副本将针对您搜索的用户名进行过滤,第二个将返回该用户的所有朋友:

select uf.name
from users u
inner join friendships fs on u.id in (fs.friend1_id, fs.friend2_id)
inner join users uf on uf.id in (fs.friend1_id, fs.friend2_id) and uf.id <> u.id
where u.name = ?

Replace ?更换? with the name of the user whose friends you want in the results.与您希望其朋友出现在结果中的用户的名称。

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

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