加入2个表的问题

时间:2009-07-21 20:07:43

标签: php sql mysql join while-loop

我想加入2张桌子,但我无法让它发挥作用。

这些是表格:
主题: id, title
帖子: thread_id, message

$sql = mysql_query("SELECT threads.id, threads.title
                    FROM threads
                    JOIN posts ON posts.thread_id = threads.id
                    WHERE threads.id = ".intval($_GET['id']));


while ($post = mysql_fetch_assoc($sql))
{
    echo $post['title'];
    echo $post['message'];

}

获得标题但不是消息。我有一个分配到该主题。

4 个答案:

答案 0 :(得分:3)

您没有选择posts.message。将您的SQL更改为此可能会有效。

SELECT threads.id, threads.title, posts.message
FROM threads
JOIN posts ON posts.thread_id = threads.id
WHERE threads.id = $id

答案 1 :(得分:1)

是否有thread_id$id匹配的帖子?因为,如果没有,那将产生一个空的结果集。

答案 2 :(得分:0)

你可以在没有PHP的情况下在MySQL中运行吗?我依靠phpMyAdmin来解决查询问题。一旦我更直接地在MySQL中获取它,phpMyAdmin就有一个“导出SQL for PHP”功能。

答案 3 :(得分:0)

如果你想获取帖子,你可能想以另一种方式去做

SELECT threads.id, threads.title, posts.message
FROM posts
JOIN threads ON threads.id = posts.thread_id
WHERE posts.thread_id = $id
相关问题