从三个表中正确加入查询

时间:2014-11-06 18:50:29

标签: mysql join

我有四张桌子:

categories table ->idcat(int), cat(varchar); 
topics table     ->idtopic(int), topic(varchar), idcat(int-fk), iduser(int-fk); 
replies table    ->idreply(int), reply(varchar) iduser(int-fk), idtopic(int-fk)
users table      ->iduser(int), username(varchar).  

我正在尝试使用JOIN编写SQL查询以获取topicuserreplies的数量。我的查询得到topiciduser但不知道如何编写它以提取user(而不是iduser)和replies所有在同一个查询中的主题(以某种方式加入idtopic)。非常感谢帮助!

SELECT t.topic, t.idtopic, t.iduser 
FROM topics t 
LEFT JOIN categories c ON t.idcat = c.idcat WHERE c.idcat = '" . $idcat . "'";   

$ idcat是传递的4个'idcat'变量之一。

2 个答案:

答案 0 :(得分:0)

我假设表iduser中的topics是创建主题的用户的ID?如果是,你可以这样做:

SELECT t.topic, t.idtopic, u.username, COUNT(r.idreply) AS cnt
FROM topics t 
LEFT JOIN categories c ON t.idcat = c.idcat WHERE c.idcat = '" . $idcat . "'"
LEFT JOIN users u ON t.iduser = u.iduser
LEFT JOIN replies r ON t.idtopic = r.idtopic
GROUP BY t.topic, t.idtopic, u.username;

答案 1 :(得分:0)

试试吧

SELECT t.topic, t.idtopic, u.username
    FROM topics t 
    LEFT JOIN categories c ON t.idcat = c.idcat 
LEFT JOIN users u ON t.iduser = u.iduser 
WHERE t.idcat = '" . $idcat . "'"