0

作为一个新秀,我对如何解决这个问题有点迷茫。我正在尝试加入三个表。这是表结构:

Accounts Table: 

1) id
2) User_id (Id given to user upon sign up)
3) Full_name 
4) Username
5) Email
6) Password

Contacts Table: 

1) My_id (This is the user who added friend_id)
2) Contact_id (this is the contact who was added by my_id)
3) Status (status of relationship)

Posts Table: 

1) Post_id
2) User_posting (this is the user who posted it)
3) Post_name
4) User_allowed (this is where its specified who can see it)

这是我的代码结构:

<?php

$everybody = "everybody";
$sid = "user who is logged in.";

$sql = <<<SQL
SELECT DISTINCT contacts.contact_id, accounts.full_name, posts.post_id, posts.post_name
FROM contacts, accounts, posts
WHERE
    (contacts.my_id = '$sid'
      AND contacts.contact_id = accounts.user_id)
    OR (contacts.my_id = '$sid'
      AND contacts.contact_id = accounts.user_id)
    OR (posts.user_posting = '$sid'
      AND contacts.contact_id = accounts.user_id
      AND posts.user_allowed = '$everybody')
    OR (posts.user_id = '$sid'
    AND contacts.user_id = accounts.user_id
    AND posts.user_allowed = '$everybody')

LIMIT $startrow, 20;


$query = mysql_query($sql) or die ("Error: ".mysql_error());

$result = mysql_query($sql);

if ($result == "")
{
echo "";
}
echo "";


$rows = mysql_num_rows($result);

if($rows == 0)
{
print("");

}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{

$contactid = htmlspecialchars($row['contact_id']);
$name = htmlspecialchars($row['full_name']);
$postid = htmlspecialchars($row['post_id']);
$postname = htmlspecialchars($row['post_name']);

// If $dob is empty
if (empty($contactid)) {

$contactid = "You haven't added any friends yet.";
}


print("$contactid <br>$postname by $name <br />");
}

}

问题是查询显示了我的帖子以及朋友的所有帖子。

我究竟做错了什么?

4

2 回答 2

1

应该是这样的(未彻底检查):

SELECT DISTINCT contacts.contact_id, 
                accounts.full_name,
                posts.post_id, 
                posts.post_name 
FROM contacts
INNER JOIN accounts ON accounts.id = contacts.id
INNER JOIN posts ON posts.User_posting = accounts.id /* (where'd get posts.user_id btw ) */
WHERE contacts.my_id = $sid
      AND posts.user_allowed = $everybody
LIMIT $startrow, 20
于 2012-05-08T16:34:58.250 回答
1

假设您只想显示您朋友的帖子(而不是您自己的帖子):

$everybody = "everybody";
$sid = user who is logged in.  

$sql = "SELECT a.User_id, a.Full_name, p.Post_id, p.Post_name
FROM posts p
INNER JOIN accounts a ON a.User_id = p.User_posting
INNER JOIN contacts c ON c.My_id = '$sid' AND c.Contact_id = a.User_id
WHERE p.User_allowed = '$everybody'
LIMIT $startrow, 20";

编辑:解释查询。

  1. 查询SELECT的某些字段用于输出
  2. FROMposts表因为结果应该包含每个帖子的一行。
  3. 该基表JOINaccounts表编辑以获取发布用户的数据,并且
  4. 额外添加JOINcontacts表格,因此我们可以过滤以仅发布也是相关用户添加的朋友的用户。
  5. 一个额外的过滤器位于允许的值上,并且
  6. 出于分页目的,我们有一个由 定义的偏移量$startrow
于 2012-05-08T16:36:34.213 回答