我将在之前的StackOverflow帖子中引用本指南:
"Table Name: User
Columns:
UserID PK
EmailAddress
Password
Gender
DOB
Location
TableName: Friends
Columns:
UserID PK FK
FriendID PK FK
(This table features a composite primary key made up of the two foreign
keys, both pointing back to the user table. One ID will point to the
logged in user, the other ID will point to the individual friend
of that user)
Example Usage:
Table User
--------------
UserID EmailAddress Password Gender DOB Location
------------------------------------------------------
1 bob@bob.com bobbie M 1/1/2009 New York City
2 jon@jon.com jonathan M 2/2/2008 Los Angeles
3 joe@joe.com joseph M 1/2/2007 Pittsburgh
Table Friends
---------------
UserID FriendID
----------------
1 2
1 3
2 3"
现在,我完成了所有这些,并且我已经创建了这个查询:
if ($_SESSION["user_id"]) {
$user_id = $_SESSION["user_id"];
$query = "SELECT * ";
$query .= "FROM friends ";
$query .= "WHERE ";
$query .= "user_id OR friend_id = '{$user_id}' ";
$result = mysqli_query($connection, $query);
$result_set = mysqli_fetch_assoc($result);
print_r($result_set);
耶!这个print_r获取了我期望的关联数组。 但是现在,因为user_id或friend_id可以是登录用户,所以我很难知道我需要使用什么样的查询才能真正显示好友列表。
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE id = ''
由于我的困惑,这就是我所知道的。 朝着正确方向的任何一点都会令人惊叹。谢谢!
答案 0 :(得分:0)
<强> PHP 强>
$reg_no = $_SESSION["user_id"];
SQL QUERY:
select * from `User` join `friends` on '$reg_no' = `friends`.`UserID` and `User`.`UserID` = `friends`.`UserID` or '$reg_no' = `FriendID` and `User`.`UserID` = `friends`.`UserID`;
尝试......
答案 1 :(得分:0)
哦,我明白了。您(用户)想要显示您的朋友(其他用户)
试试这个:
SELECT U.EmailAddress, U.Gender, U.DOB, U.Location FROM User U
LEFT JOIN Friends F on U.UserID = F.Friend_ID WHERE F.User_ID = 1;
然后只需将1更改为登录用户ID的任何内容。
干杯!