2015-08-16 85 views
2

我想将我的用户表添加到我现有的查询中,以便我可以将users.id与forum_topics.topic_creator进行匹配,以便我可以匹配这些并使自己能够分配与该用户的用户名。添加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 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)); 

我收到故障消息。

我在做什么错?

回答

2

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 
+0

好吧,这不是给我任何错误,但我的用户名不输出。我将这个用户名列字段分配给它,就像这样..'$ creator = $ row2 ['username'];' – Becky

+0

经过进一步的审查,这抛弃了原始查询的目的。我也有这个链接。当我点击这个链接时,什么也没有显示出来 – Becky

+0

@Becky:你在表'forum_topics'中有用户名字段吗? (这是select子句中唯一使用的表)我想,它在表'users'中。你还没有尝试从表'用户'中选择它。 –

1

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)); 
0

试试这个

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`