从最新的5个帖子中选择所有标签分配

时间:2012-06-17 19:06:35

标签: php mysql tags blogs posts

我有三张桌子:

  1. post(id) - 包含所有条目
  2. tag(id) - 包含所有标记
  3. assign(post_id,tag_id) - 为帖子指定标签,可能有多个帖子行
  4. 这是我到目前为止所做的:

      

    $ sql_post = mysql_query(“SELECT title,content,time,web FROM post ORDER BY time DESC LIMIT 5”);

         

    $ sql_tag = mysql_query(“SELECT tag.name,tag.id,post.id FROM assign LEFT JOIN tag ON assign.tag_id = tag.id LEFT JOIN post ON assign.post_id = post.id WHERE post.time> (SELECT MIN(time)FROM(SELECT time FROM post ORDER BY time DESC LIMIT 6)two)“);

    我想把它全部放在一个大数组中,所以像这样(草率摘要):

    array(
        post_id => array(
            "title" => "post's title...",
            "content" => "post's content...",
            "tag" => array(
                tag_id => "tag 1's name",
                tag_id => "tag 2's name
    

    ...然后使用foreach将它们显示在我的博客上。

    我需要帮助的地方是$sql_tag的sql。我该怎么做才能选择最新5个帖子的所有作业?它只为帖子选择一个标签。

2 个答案:

答案 0 :(得分:0)

为什么不循环你感兴趣的帖子?

$sql_post = mysql_query("SELECT id, title,content,time,web FROM post ORDER BY time DESC LIMIT 5");

while ($row = mysql_fetch_assoc($sql_post)) {
     $sql_tag = mysql_query("SELECT tag.name,post.id FROM assign LEFT JOIN tag ON assign.tag_id=tag.id WHERE assign.post_id='".$row['id']."'");
}

答案 1 :(得分:0)

尝试:

SELECT
    c.id,
    c.name,
    a.id
FROM
    (
        SELECT id
        FROM post
        ORDER BY time DESC
        LIMIT 5
    ) a
LEFT JOIN
    assign b ON a.id = b.post_id
LEFT JOIN
    tag c ON b.tag_id = c.id