簡體   English   中英

如何連接三個表並添加“AND”運算符?

[英]How to join three tables and add a “AND” operator?

作為一個新秀我有點迷失如何釘這個。 我想加入三張桌子。 這是表結構:

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 />");
}

}

問題是查詢顯示我的帖子以及朋友的所有帖子。

我究竟做錯了什么?

應該是這樣(沒有徹底檢查):

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

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

$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. FROM posts表中,因為結果應該包含每個帖子的一行。
  3. 該基表與accounts表一起JOIN以獲取發布用戶的數據
  4. 另外JOIN contacts表格,這樣我們就可以過濾到只有相關用戶添加的朋友的帖子用戶。
  5. 額外的過濾器在允許的值和
  6. 為了分頁,我們有一個由$startrow定義的偏移量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM