使用sql获取子项?

时间:2012-09-08 22:13:56

标签: php mysql arrays multidimensional-array

我有三张桌子,

EntriesTagsEntry_Tag_Link

我的查询通过并从Entries

中提取所有内容
SELECT *
FROM (`blog_entries`)
ORDER BY `date` desc

我最终得到了一系列条目。

之后我循环播放

foreach($entries as &$entry)
    $entry['tags'] => getTags($entry['id]);

getTags函数运行此查询

SELECT t.* 
FROM blog_tags t
JOIN blog_entries_tags_link l
    ON t.id = l.tag_id
WHERE l.entry_id = {whatever id was passed}
ORDER BY t.name asc;

所以我最终得到一个看起来像的数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => First Title
            [tags] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [name] => t1
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [name] => t2
                        )

                )

        )

    [1] => Array
        (
            [id] => 2
            [title] => Second Title
            [tags] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [name] => t1
                        )

                    [1] => Array
                        (
                            [id] => 3
                            [name] => t3
                        )

                )

        )

)

那么,这意味着如果有200个条目,我最终会得到201个查询, 我想知道是否有办法在一个查询中获取我需要的所有数据(然后假设用php将其按到正确的格式)?

2 个答案:

答案 0 :(得分:1)

答案是肯定的,至少从SQL的角度来看。

SELECT t.* 
FROM blog_tags t join
     blog_entries_tags_link l
     ON t.id = l.tag_id join
     (SELECT *
      FROM `blog_entries` e
     ) e
     on l.entry_id = e.entry_id
WHERE l.entry_id = {whatever id was passed}
ORDER BY e.`date` desc, t.name asc

这假设每个blog_entry的id都是唯一的(并且您的代码建议就是这种情况)。

答案 1 :(得分:1)

我假设您的博客条目ID是blog_entry_id ...

请求:

SELECT b.title, t.entry_id, t.name, l.tag_id 
FROM blog_entries b
JOIN blog_tags t on t.entry_id = b.blog_entry_id
JOIN blog_entries_tags_link l on t.id = l.tag_id
ORDER BY b.date DESC, t.name ASC

PHP:

$result = array();
foreach ($entries as $entry) {

    // Creates a new blog entry on the $result array
    if (!isset($result[ $entry['entry_id'] ])) {
        $blog_entry = array();
        $blog_entry['id'] = $entry['entry_id'];
        $blog_entry['title'] = $entry['title'];
        $blog_entry['tags'] = array();
        $result[ $entry['entry_id'] ] = $entry;
    }

    // Add a new tag
    $tag = array();
    $tag['id'] = $entry['tag_id'];
    $tag['name'] = $entry['name'];
    $result[ $entry['entry_id'] ]['tags'][] = $tag;

}

您可能会注意到,您从未使用过blog_entry_tags_link(我之所以使用它只是因为我不知道您的列名)。