SQL联接两个不同的表

时间:2019-05-04 19:06:54

标签: php mysql json

表中有列:

friends:  id | id1 | id2 | accepted | notification

users:    id | username | email | password

朋友中的id1始终是朋友请求的发送者,而id2是他的朋友。

$sql = "SELECT * FROM friends WHERE id1='$id' AND accepted=1 AND notification=1;";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

header("Content-Type: application/json");
echo json_encode($data);

$ id来自会话。我想从id(in users)= id2(if friends)的用户那里获取用户名

$ sql看起来如何?

2 个答案:

答案 0 :(得分:0)

不确定您要达到的逻辑目标。 这是什么意思:id(在用户中)= id2(如果是朋友)?你能用文字描述吗?

也许这样的事情可能会为如何进行提供一个见解:

SELECT 
   sender.id1 as senderID,
   u.username as senderUsername,
   receiver.id1 as receiverID,
   u.username as receiverUsername
FROM users u 
INNER JOIN friends sender ON u.id = sender.id1
INNER JOIN friends receiver ON u.id = receiver.id2
WHERE sender.id1='$id' 
  AND receiver.accepted=1
  AND receiver.notification=1;

答案 1 :(得分:0)

使用此查询可获得所需的结果。

$ sql =“从朋友中以f JOIN用户身份选择f.id,f.id1,f.id2,f.accepted,f.notification,u.id,u.username,u.email和u.password u ON u.id = f.id2其中f.accepted ='1'AND f.notification ='1'“;