向查询添加 JOIN 导致失败
Posted
技术标签:
【中文标题】向查询添加 JOIN 导致失败【英文标题】:Adding a JOIN to query resulting in a fail 【发布时间】:2015-08-16 07:33:41 【问题描述】:我正在尝试将我的 users 表添加到我现有的查询中,以便我可以将 users.id 与 forum_topics.topic_creator 进行匹配,这样我就可以将它们匹配并允许自己将其分配给该用户的用户名。
这是我的原始查询。
$query2 = mysqli_query($con,"SELECT t.*, COUNT(p.topic_id)
AS tid2 FROM forum_topics AS t JOIN forum_posts
AS p on t.id = p.topic_id WHERE t.category_id = ".$cid."
GROUP BY t.id DESC")
然后我尝试这样做..
$query2 =mysqli_query($con,"SELECT t.*, COUNT(p.topic_id)
AS tid2 FROM forum_topics AS t JOIN forum_posts
AS p on t.id = p.topic_id WHERE t.category_id = ".$cid."
INNER JOIN users AS u
ON t.topic_creator = u.id
GROUP BY t.id DESC")
or die ("Query2 failed: %s\n".($query2->error));
我收到失败消息。
我做错了什么?
【问题讨论】:
【参考方案1】:WHERE
子句应该在之后加入:
SELECT t.*, COUNT(p.topic_id) AS tid2
FROM forum_topics AS t JOIN
forum_posts AS p on t.id = p.topic_id INNER JOIN
users AS u ON t.topic_creator = u.id
WHERE t.category_id = ".$cid."
GROUP BY t.id DESC
编辑:
同时选择username
:
SELECT t.*,u.username, COUNT(p.topic_id) AS tid2
FROM forum_topics AS t JOIN
forum_posts AS p on t.id = p.topic_id INNER JOIN
users AS u ON t.topic_creator = u.id
WHERE t.category_id = ".$cid."
GROUP BY t.id DESC
【讨论】:
好的,这没有给我任何错误,但我的用户名没有输出。我正在为它分配用户名列字段,如下所示..$creator = $row2['username'];
经过进一步审查,这偏离了原始查询的目的。我也将其与链接相关联。当我点击链接时,什么都没有显示
@Becky:forum_topics
表中有用户名字段吗? (那是 select 子句中使用的唯一表)我猜,它在表 users
中。而且您还没有尝试从表 users
中选择它。
不,forum_topics
表中没有用户名字段。我有 topic_creator,它是一个与 users
id 匹配的整数。
@Becky:然后从 users 表中选择用户名。请参阅我的答案中的编辑。【参考方案2】:
WHERE
子句必须放在INNER JOIN
之后。
$query2 =mysqli_query($con,"SELECT t.*, COUNT(p.topic_id)
AS tid2 FROM forum_topics AS t
JOIN forum_posts AS p ON t.id = p.topic_id
INNER JOIN users AS u ON t.topic_creator = u.id
WHERE t.category_id = ".$cid."
GROUP BY t.id DESC")
or die ("Query2 failed: %s\n".($query2->error));
【讨论】:
【参考方案3】:试试这个
SELECT t.*, COUNT(p.topic_id) AS tid2
FROM forum_topics t
JOIN forum_posts p ON (t.id = p.topic_id )
INNER JOIN users u ON (t.topic_creator = u.id)
WHERE t.category_id = ".$cid."
GROUP BY t.id DESC`
【讨论】:
以上是关于向查询添加 JOIN 导致失败的主要内容,如果未能解决你的问题,请参考以下文章
使用 Informix 和 Dapper 向查询添加参数失败并出现语法异常
微信页面script标签添加crossorigin=“anonymous”导致页面加载失败
在 Spring Boot 中向本机查询添加参数会导致“org.hibernate.exception.SQLGrammarException”,