如何连接多个表并将结果返回到屏幕?

时间:2016-01-11 21:59:00

标签: php mysql

我有四张桌子:

users (id, username, password);
topics (id, uid, name, date);
subjects (id, uid, tid, name, date);
posts (id, sid, tid, content, date);

我想按照日期顺序回应每个主题的主题和帖子数量。

我的查询如下:

$tquery = 'SELECT users.id, users.username, 
                  topics.id, topics.name, topics.date, topics.uid, 
                  subjects.tid, subjects.id, posts.sid FROM topics
               INNER JOIN users ON topics.uid = users.id
               INNER JOIN subjects ON subjects.tid = topics.id
               INNER JOIN posts ON posts.sid = subjects.id
           ORDER BY topics.date DESC';
$res = mysqli_query($connection, $tquery);

用于回显主题的PHP代码如下:

while ($row = mysqli_fetch_assoc($res)){
    echo '<table><tr class="heading">
                <th title="Hozzáadta: admin '.$row["username"].'"><a href="/php/forum/topics.php?id='.$row["id"].'" class="topic-title">'.$row["name"].'</a></th>
                <th>Témák: '.count($row["tid"]).'</th>
                <th>Hozzászólások: '.count($row["sid"]).'</th>
                <th>Hozzáadva: '.$row["date"].'</th>
            </tr></table>';
}

不幸的是,这是错误的,因为它会返回具有相同主题名称的表格,并且它也不会对主题和帖子进行计数。请帮助我几天前我已经解决了这个问题。

1 个答案:

答案 0 :(得分:0)

在SQL中使用group bycount而不是在php:

SELECT users.id, users.username, topics.id, topics.name, topics.date, topics.uid, count(subjects.tid), subjects.id, count(posts.sid) FROM topics
left JOIN users ON topics.uid = users.id
left JOIN subjects ON subjects.tid = topics.id
left JOIN posts ON posts.sid = subjects.id
group by topics.id
ORDER BY topics.date DESC