2014-09-12 134 views
0

我会根据关本指南中先前StackOverflow的帖子:PHP/MySQL的 - 好友列表SQL查询

"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  [email protected] bobbie M  1/1/2009 New York City 
2  [email protected] jonathan M  2/2/2008 Los Angeles 
3  [email protected] 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

除了没有'$ user_id'值,你写的第二个查询出了什么问题?什么返回? – 2014-09-12 19:51:39

回答

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是登录。

干杯!

+0

谢谢蒂姆!我从未使用过“你”。格式之前。当你把“从用户U”,你的“用户”实际上应该是我的表的名称,这是“用户”的小写字母u,或者是所需的资本? 编辑:哦,即时通讯抱歉。在这个例子中,表格实际上被命名为。这是我的,名字不同。非常感谢你,我明白了! – diabetesjones 2014-09-12 21:05:55

+0

tim,你认为theres无论如何可以用英语分解这个MySQL查询为我完全执行吗?我已经在它没有产生任何错误的地方,但是一旦它完成,我仍然无法在这个查询中得到print_r($ result_set)。编辑:它工作。我工作得很好。非常感谢你tim :) – diabetesjones 2014-09-12 21:18:37

+0

嘿,男人没问题。这个MySQL查询所做的是从所有用户中选择电子邮件地址,性别,出生日期和位置,然后加入Friends表(使用Friends.Friend_ID = Users.UserID列),然后仅显示Friends.User_ID = The选定的ID。这是一个更复杂的连接,但我很高兴你得到它的工作:) – 2014-09-15 14:31:17

0

PHP

$reg_no = $_SESSION["user_id"]; 

SQL查询:

select * from `User` join `friends` on '$reg_no' = `friends`.`UserID` and `User`.`UserID` = `friends`.`UserID` or '$reg_no' = `FriendID` and `User`.`UserID` = `friends`.`UserID`; 

TRY IT ....