0

对不起,复杂的标题。

我有这个架构:

Categories  Albums          Photos 
----------  -------         --------
id          id              id
name        category_id     album_id

从这些表中,我需要构建一个导航菜单,如下所示:

Category1
   album1
   album2
Category2
   album3
Category3
   album4

我可以轻松地构建它,但现在我只想显示至少包含一张照片的相册和至少包含一张相册的类别。我该怎么做?

编辑:我正在使用 Codeigniter,现在我正在这样做:

在控制器中,我使用两个简单的查询构建了一个数组

 $categories = $this->category->get_categories();

    foreach ($categories as $category)
    {
        $data['categories'][$category->name] = $this->album->get_albums_by_category($category->id);
    }

get_categories() 查询:

    function get_categories()
{
    $this->db->select('*')->
        from('categories');
    return $this->db->get()->result();
}

和 get_albums 之一:

    function get_albums_by_category($category_id)
{
    // per stampare il nome dell'album nella lingua giusta
    $lang = $this->lang->lang();
    $name = $lang . '_name';
    $this->db->select('id, ' . $name . ' AS name')
        ->from('albums')
        ->group_by('id')
        ->where('category_id', $category_id);
    return $this->db->get()->result();
}

我使用了两个查询,这样我就可以成为我需要的数组。

4

2 回答 2

1

让我们从您的基本查询开始:

select (case when thetype = 'Category' then category else album end) as what
from ((select 'category' as thetype, category, NULL as album
       from category
      ) union all
      (select 'album', category, album
       from album a join
            category c
            on a.category_id = c.id
      )
     ) t
order by category, album

现在,我们可以针对您的问题进行修改:

select (case when thetype = 'Category' then category else album end) as what
from ((select 'category' as thetype, category, NULL as album
       from categories c
       where c.id in (select category_id from albums)
      ) union all
      (select 'album', category, album
       from albums a join
            categories c
            on a.category_id = c.id
       where a.id in (select album_id from photos)
      )
     ) t
order by category, album
于 2012-07-10T13:43:00.463 回答
0

使用这种技术:

SELECT * 
FROM Albums
WHERE EXISTS (
    SELECT 1
    FROM Photos
    WHERE Photos.album_id = Album.id
)

这称为相关子查询,如果将其用于完全连接,在某些情况下可能会很慢,但在这里仅使用 EXISTS 子句,它应该很快。

于 2012-07-10T13:40:20.560 回答