让 JOIN 工作的问题
Posted
技术标签:
【中文标题】让 JOIN 工作的问题【英文标题】:Issue getting JOIN to work 【发布时间】:2015-08-18 06:01:43 【问题描述】:我有以下查询
$stmt2 = $con->prepare("SELECT `id`, `category_id`, `topic_id`, `post_creator`, `post_content`, `post_date` FROM forum_posts WHERE `category_id`=? AND `topic_id`=?");
我现在正在尝试加入我的用户表,以便将forum_posts.post_creator
与users.id
匹配并从中获取用户名。
我正在尝试这个,但查询一直失败..
$stmt2 = $con->prepare("SELECT forum_posts.id, forum_posts.category_id, forum_posts.topic_id, forum_posts.post_creator, forum_posts.post_content, forum_postspost_date FROM forum_posts
WHERE forum_posts.category_id=? AND forum_posts.topic_id=?
INNER JOIN users
ON forum_posts.post_creator = users.id");
if ( !$stmt2 || $con->error )
// Check Errors for prepare
die('Stmt2 SELECT prepare() failed: ' . htmlspecialchars($con->error));
$stmt2->bind_param("ii", $cid, $tid);
if(!$stmt2->execute())
die('Stmt2 SELECT execute() failed: ' . htmlspecialchars($stmt2->error));
$stmt2->store_result();
$stmt2->bind_result($post_id, $post_category_id, $post_topic_id, $post_creator, $post_content, $post_date, $posts_username);
我收到此错误,但无法弄清楚该部分有什么问题。
Stmt2 SELECT prepare() failed: You have an error in your SQL syntax; check the manual that corresponds to your mysql server version for the right syntax to use near 'INNER JOIN users ON forum_posts.post_creator = users.id' at line 3
我做错了什么?
【问题讨论】:
【参考方案1】:inner join
是from
子句的一部分,而不是where
子句的一部分:
SELECT forum_posts.id, forum_posts.category_id, forum_posts.topic_id, forum_posts.post_creator, forum_posts.post_content, forum_postspost_date
FROM forum_posts
INNER JOIN users
ON forum_posts.post_creator = users.id
WHERE forum_posts.category_id=? AND forum_posts.topic_id=?
【讨论】:
我应该忽略这部分吗?users.username
@Paul 在您的问题中找不到这部分
对不起.. 我会这样做来获取用户名吗? SELECT forum_posts.id, forum_posts.category_id, forum_posts.topic_id, forum_posts.post_creator, forum_posts.post_content, forum_postspost_date, users.username
是的。你可以用它来获取username
效果很好!谢谢!【参考方案2】:
你准备好的陈述应该是这样的。 JOIN
应该在 Where
之前
("SELECT forum_posts.id, forum_posts.category_id, forum_posts.topic_id,
forum_posts.post_creator, forum_posts.post_content, forum_postspost_date
FROM forum_posts INNER JOIN users
ON forum_posts.post_creator = users.id
WHERE forum_posts.category_id=? AND
forum_posts.topic_id=?"
);
【讨论】:
以上是关于让 JOIN 工作的问题的主要内容,如果未能解决你的问题,请参考以下文章
Thread.join() 在 Dining Philosophers 实现中无法正常工作