2012-02-08 60 views
1

數據庫模式http://pastebin.com/aPXk1rMf使用多個MySQL的加入

我要選擇「信息發佈者的UNAME」和「評論業主UNAME」從「意見」表(即我想我需要cOwnerID> uName和pID> uID> uName),這樣我可以在發佈評論後立即登錄一些活動。 我試圖使用MySQL連接爲了實現這一點,但我不能;所以這是我徒勞的嘗試。

$result = dbquery("INSERT INTO comments VALUES ('','$pID','$ownerID','$cmnt')"); // inserting a comment 

$lastID = mysql_insert_id(); 

$res = dbquery("SELECT 
       users.username AS username 
      FROM `comments` 
      LEFT JOIN `users` on comments.cOwnerID = users.uID 
      WHERE (cID='$lastID')"); 

回答

1

我認爲你必須爲表格用戶使用別名,因爲實際上,你將在這個表格上有兩個連接:一個用於發佈作者,另一個用於評論作者。

嘗試這樣:

  SELECT 
       commentAuthor.username AS commentauthor_username, 
       postAuthor.username AS postauthor_username 
      FROM `comments` 
      LEFT JOIN `users` AS commentAuthor on comments.cOwnerID = commentAuthor.uID 
      LEFT JOIN `posts` on posts.pId = comments.pID 
      LEFT JOIN `users` AS postAuthor on posts.uID = postAuthor.uID 
      WHERE (cID='$lastID') 
1
SELECT users1.username, users2.username FROM Posts p 
WHERE p.pID="$POST_OF_INTEREST" 
LEFT JOIN users users1 ON users1.uID=p.uID 
LEFT OUTER JOIN comments ON comments.pID=p.pID 
LEFT OUTER JOIN users users2 ON users2.uID=comments.cOwnerID 

對於一個特定的帖子ID,這將讓誰張貼的人的用戶名和每一個誰上後(根據註釋一行)評論人的用戶名。

1
SELECT Users.uName AS UserNamePost 
      , UserComment.uName AS UserNameComment 
FROM Users 
INNER JOIN Posts 
    ON Posts.uID = Users.uID; 
INNER JOIN Comments 
    ON Comments.pID = Posts.pID ; 
INNER JOIN Users AS UserComment 
    ON Comments.cOwnerID = UserComment.uID ; 

這將力爭有已發佈帖子的用戶,然後加入對這個職位

0

所有評論的用戶「選擇 用戶.username AS用戶名稱, 評論.cOwnerID AS評論用戶, users.uID用戶ID 從 評論 LEFT JOIN 用戶 ON commentOwner = userID WHERE commentOwner ='{$ lastID}'「;