如果连接表中有链接的行,如何从表中选择行?

时间:2012-07-10 13:34:49

标签: sql codeigniter activerecord join

抱歉复杂的头衔。

我有这个架构:

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();
}

我使用了两个查询,以便在需要时可以成为数组。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用此技术:

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

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