[英]SQL/PHP - Calling Same Table Twice Based on Column Value
Here is a general setup of my table: 这是我的桌子的一般设置:
users
-------------
user_id | user_first | user_last | user_friendlist
1 | John | Doe | 2,3
2 | Jimmy | John | 1,3
3 | Papa | John | 1,2
I tried Left JOIN, but I am not sure how to call the same table twice... Please help! 我尝试了Left JOIN,但不确定如何两次调用同一张表...请帮助! It gets all confusing when attempting to do a prepare statement. 尝试执行prepare语句时,这一切都令人困惑。
General code for the first part: 第一部分的通用代码:
$selectData = $con->prepare("SELECT
user_friendlist
FROM
users
WHERE
user_id=?");
$selectData->bind_param("i", $user_id);
$user_id = $_POST['user_id'];
$selectData -> execute();
$selectData-> bind_result($user_friendlist);
$arr = array();
while ( $selectData -> fetch() ) {
$arr[] = $user_friendlist;
}
echo json_encode($arr);
you should have two tables users and friends 您应该有两个表的用户和朋友
users will be like 用户会喜欢
| user_id | user_first | user_last |
| 1 | John | Doe |
| 2 | Jimmy | John |
| 3 | Papa | John |
and friends 和朋友
| user_id | freind_id |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
user_id
is the program key for table users
user_id
是表users
的程序密钥
user_id
and friend_id
are the primary key for table friend
user_id
和friend_id
是表friend
的主键
friends.user_id
and friends.friend_id
is foreign keys for users.user_id
friends.user_id
和friends.friend_id
是users.user_id
外键
the query will be like 查询将像
SELECT users2.user_first AS friend_first,users2.user_last AS friend_last
-- ,users1.user_first AS user_first,users1.user_last AS user_last
-- uncomment the last line to get the user info with his friends
FROM users as users1
join friends
ON users1.user_id=friends.user_id
JOIN users AS users2
ON users2.user_id=friends.friend_id
WHERE users1.user_id=1
the query result is 查询结果是
| friend_first | friend_last |
| Jimmy | John |
| Papa | John |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.