基本上我有2张桌子
我正在尝试使用左连接,以便我可以将“主题”中的“posted_by”与“users”中的“user_id”相关联,这样我就可以同时输出users.username用于显示,以及用户.profile(头像图片)。
这是我当前的代码,它给出了布尔错误。
<?php
include 'core/init.php';
include 'includes/overall/header.php';
$sql = " SELECT *, users.id, users.username, users.profile
FROM `topics`
LEFT JOIN
users ON topics.posted_by = " . mysql_real_escape_string($_GET['topic_id']) . " users.user_id ORDER BY `posted` DESC";
$result = mysql_query($sql);
// Start looping table row
while($rows = mysql_fetch_array($result)){
?>
<table>
<tr>
<td rowspan="4"> Avatar code to go here<br>
<? echo $rows['username']; ?></td>
<td><? echo $rows['category']; ?> > <? echo $rows['sub_category']; ?> </td>
</tr>
<tr>
<td><? echo $rows['posted']; ?></td>
</tr>
<tr>
<td><? echo $rows['topic_data']; ?></td>
</tr>
<tr>
<td><a href="view_topic.php?id=<? echo $rows['topic_id']; ?>">Reply</a> (<? echo $rows['reply']; ?>) Replies</td>
</tr>
</table>
<?php
// Exit looping and close connection
}
mysql_close();
?>
答案 0 :(得分:0)
ON topics.posted_by = " . mysql_real_escape_string($_GET['topic_id']) . " users.user_id
你知道这会产生ON topics.posted_by = 1 users.user_id
例如无效的SQL语法。改用WHERE
ON topics.posted_by = users.user_id WHERE topics.id = (topic_id_variable)
P.S。:强烈建议不要使用mysql_
。您应该更改API。
答案 1 :(得分:0)
您需要在join子句中提供users
与topics
的关联方式。您已为join子句提供了外部变量。这不允许数据库引擎建立关于如何连接两个表的关系。
我相信您期望的查询应该是这样的
$sql = " SELECT *, users.id, users.username, users.profile
FROM `topics`
LEFT JOIN
users ON topics.posted_by = users.user_id
WHERE topics.id = '" . mysql_real_escape_string($_GET['topic_id']) . "'
ORDER BY `posted` DESC";
答案 2 :(得分:0)
我相信你正在使用像
这样的东西$sql = "SELECT users.user_id, users.username, users.profile, topics.topic_id, topics.category, topics.sub_category,
topics.topic_data, topics.posted_by, topics.posted, topics.view, topics.reply
FROM users WHERE topics.posted_by = users.user_id ORDER BY topics.posted DESC";
尝试添加
$ sql =“SELECT users.user_id,users.username,users.profile,topics.topic_id,topics.category,topics.sub_category, topics.topic_data,topics.posted_by,topics.posted,topics.view,topics.reply FROM 用户,主题 WHERE topics.posted_by = users.user_id ORDER BY topics.posted DESC“;