外键链接在查询中引用两次到同一个表

时间:2012-12-13 07:00:12

标签: php mysql mysqli foreign-keys

我需要一些帮助在PHP中编写mysql语句。我在同一个表中有两次引用相同的外键,我需要使用SELECT语句引用这两个实例。 I.E.我有一个名为messages的表,然后有两个标记为sender和receiver的列。两列都链接到表用户。我需要在同一个查询中从发送者 - 用户和接收者 - 用户中提取信息。我在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"

正确所以我可以包含关于message.receiver的“users.image,users.externalid,users.fname,users.lname”而不仅仅是message.sender

我在参考这个问题/答案时重写了我的代码,但随后被卡住了:ForeignKey Referencing Same Table

1 个答案:

答案 0 :(得分: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