如何在MySQL中使用外键选择一行表? [英] How to select a row of table using foreign key in MySQL?
本文介绍了如何在MySQL中使用外键选择一行表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两张表(第一个是账户,第二个是朋友)帐户在哪里
I have two tables (first is account and second is friend) where account looks like
//平板账户
id | name
1 | bob
2 | robin
3 | chan
4 | jack
//id 是主键
//桌友
id | user_id | frn_id
1 | 2 | 4
2 | 1 | 2
3 | 1 | 3
//user_id 和 frn_id 是账户主键的外键
// user_id and frn_id are foregin key from primary key of account
选择结果应该是这样的
id | user_id | frn_id
1 | robin | jack
2 | bob | robin
3 | bob | chan
那么如何以这种方式从表朋友中选择,而不是显示user_id和frn_id,我想显示表帐户中的名称.
then how to select from table friend in a such a way so that instead of showing user_id and frn_id, I want to show name from table account.
推荐答案
我做了一些内连接查询,它对我有用
I have done some inner join query and it works for me
select f.id, a1.name as 'user', a2.name as 'friend'
from friend f
INNER join account a1 on a1.id = f.user_id
INNER join account a2 on a2.id = f.frn_id
ORDER BY f.id
这篇关于如何在MySQL中使用外键选择一行表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文