SQL Join返回错误的结果

时间:2017-12-14 13:38:14

标签: php mysql sql

我正在尝试加入两个表格。表1称为帐户,它由account_id,fname,lname,picture组成,表2称为friendpending,由account_id,friend_id和message组成。我正在创建一个允许用户添加朋友的程序,当我传入account_id时,它返回用户名,我需要它来返回friend_id名称。

这是我到目前为止所尝试的:

SELECT account.fname, account.lname, account.picture
from account
INNER JOIN friendpending ON account.account_id = friendpending.account_id
WHERE friendpending.account_id = p_account_id;

2 个答案:

答案 0 :(得分:1)

如果您想要朋友的表格中的朋友姓名,那么您需要选择该字段(或字段):

SELECT friendpending.name, 
    account.fname, account.lname, account.picture 
FROM account INNER JOIN friendpending ON account.account_id = friendpending.account_id
WHERE friendpending.account_id = p_account_id;

SELECT friendpending.fname, friendpending.lname, account.picture  
FROM account INNER JOIN friendpending ON account.account_id = friendpending.account_id
WHERE friendpending.account_id = p_account_id;

或者,根据以下评论ON account.account_id = friendpending.friend_id

答案 1 :(得分:0)

无论您想要返回什么,都需要包含在查询的SELECT部分​​中。

尝试这样的事情:

SELECT friendpending.friend_id, 
friendpending.name, 
account.fname,
account.lname,
account.picture 
FROM account
INNER JOIN friendpending ON account.account_id = friendpending.account_id
WHERE friendpending.account_id = p_account_id;