简体   繁体   English

Sql连接两个不同的表

[英]Sql join two different tables

There are colums in tables: 表中有colums:

friends:  id | id1 | id2 | accepted | notification

users:    id | username | email | password

id1 in friends is always sender of friends request and id2 is his friend. 朋友中的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 is taken from session. $ id取自会话。 I want to get username from users where id(in users)=id2(if friends) 我想从用户获取用户名,其中id(在用户中)= id2(如果是朋友)

how will $sql look like? $ sql怎么样?

Not sure what you are trying to achieve in logic. 不确定你想要在逻辑上实现什么。 What does this means : id(in users)=id2(if friends)? 这意味着什么:id(在用户中)= id2(如果是朋友)? can you describe in words 你能用语言描述吗?

Maybe something like this might give an insight on how to proceed : 也许这样的事情可能会让我们深入了解如何继续:

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;

Use this query to get ypur desired results. 使用此查询可获得所需的ypur结果。

$sql = "select f.id, f.id1,f.id2 , f.accepted,f.notification,u.id, u.username,u.email, u.password from friends as f JOIN users as u ON u.id = f.id2 Where f.accepted = '1' AND f.notification = '1' "; $ sql =“从朋友那里选择f.id,f.id1,f.id2,f.accepted,f.notification,u.id,u.username,u.email,u.password作为联合用户.id = f.id2其中f.accepted ='1'AND f.notification ='1'“;

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

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