2012-12-13 121 views
0

我需要一些幫助在PHP中編寫mysql語句。我在同一個表中引用了兩次相同的外鍵,我需要使用SELECT語句引用兩個實例。 I.E.我有一個稱爲消息的表,然後是兩列標記爲發送者和接收者。兩列都鏈接到表格用戶。我需要從發件人用戶和接收者用戶那裏獲取相同查詢中的信息。我見過的StackOverflow上其他的答案,但我似乎並沒有被正確地做它:/外鍵鏈接引用兩次查詢中的同一個表

這裏是PHP我目前的mysqli調用只有抓住寄件人用戶鏈接:

require_once('includes/connection.inc.php'); 

$db = dbConnect(); 

$stmt = $db->stmt_init(); 

$stmt = $db->prepare(" 
SELECT message.timestamp, message_type.type, 
message.sender, message.receiver, message.sender_language, 
language.translate_code, message.subject_translate, message.body_translate, 
message.subject, message.body, users.image, users.externalid, users.fname, 
users.lname FROM message 
INNER JOIN users ON message.sender=users.id 
INNER JOIN language ON message.sender_language=language.id 
INNER JOIN message_type ON message.type=message_type.id 
WHERE (message.receiver=? AND message.archived='n') 
ORDER BY message.timestamp DESC 
LIMIT 0,10 "); 

$stmt->bind_param('i', $session_id); 

$stmt->execute(); 

$stmt->bind_result($row['date'], $row['message_type'], $row['sender'], 
$row['receiver'], $row['sender_language'], $row['sender_language_code'], 
$row['subject'], $row['body'], $row['subject_original'], 
$row['body_original'], $row['image'], $row['user_name'], $row['fname'], 
$row['lname']); 

$record_count = 0; 

while($stmt->fetch()){... 

此代碼工作正常,但我需要正確添加

"INNER JOIN users ON message.receiver=users.id" 

,所以我可以包括「users.image,users.externalid,users.fname,users.lname」關於message.receiver而不僅僅是消息。發件人

我重寫我的代碼參照這個問題/答案,但隨後就死:ForeignKey Referencing Same Table

回答

3

使用別名嘗試這種策略:

SELECT msg.id, sender.id, receiver.id 
FROM message msg 
INNER JOIN users sender ON msg.sender=sender.id 
INNER JOIN users receiver ON msg.receiver=receiver.id 
WHERE [PUT_THE_WHERE_CONDITIONS_HERE] 
ORDER BY message.timestamp DESC 
LIMIT 0,10 
+1

這工作。我遇到了message.timestamp的短暫呃逆。我不得不把它寫成msg.timestamp。一旦你聲明瞭一個別名,你必須先使用它,然後...... – vinsanity38

相關問題