我需要一些帮助在 PHP 中编写 mysql 语句。我在同一个表中引用了两次相同的外键,我需要使用 SELECT 语句引用这两个实例。IE 我有一个名为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 而不仅仅是 message.sender 的“users.image,users.externalid,users.fname,users.lname”
我正在参考这个问题/答案重写我的代码,但后来卡住了:ForeignKey Reference Same Table