使用连接和数据透视表选择mysql

时间:2015-04-28 22:49:31

标签: mysql join pivot-table

我有4个表:品牌,类别,brands_category和文件。 品牌和类别由brands_category链接,brands_category有2列:brand_id和category_id

## brands ##
id  |  name |  url | ..

## category ##
id | name | order | ..

## brands_category ##
brand_id | category_id

## files ##
id | name | path | brand_id | uploaded_at

我希望从文件表中获取所有具有特定类别且按来自upload_at的不同品牌,而不重复品牌。 我做了不少尝试,但无法得到我想要的结果。 这是我取得的最大成功:

SELECT b.*, aa.uploaded_at
   FROM   brands b
   INNER JOIN
  (SELECT   bc.brand_id, f.uploaded_at
               FROM     brands_category bc
                        INNER JOIN brands b
                          ON b.id = bc.brand_id

                        INNER JOIN category c
                          ON c.id = bc.category_id
               INNER JOIN files f
               ON f.brand_id = bc.brand_id
               WHERE    c.id = 1
                GROUP BY bc.brand_id ORDER BY bc.brand_id DESC, f.uploaded_at DESC) aa
       ON b.id = aa.brand_id

我确实获得了类别为1的品牌,但是当品牌有多个与之关联的文件时,最新的uploaded_at日期不会返回。

1 个答案:

答案 0 :(得分:0)

不需要pivot表 - 只需使用标准joins

select b.brand_id
from brands b
    join brands_category bc on b.brand_id = bc.brand_id
    join category c on bc.category_id = c.category_id
    join files f on b.brand_id = f.brand_id
where c.category_name = 'Some Category'
order by f.uploaded_at