0

我想要一个用于以下场景的 mysql 查询我有以下数据库结构

1] table 'albums'  Columns  'id', 'name'
2] table 'tracks'  Columns  'id', 'title', 'album_id'   (album has many tracks)
3] table 'assets'  Columns  'id', 'track_id'   (track has many assets)

我想找出所有专辑,该专辑的所有曲目必须至少有 2 个资产。

对于以下测试数据专辑

'id'    'name'
  1      Album 1
  2      Album 2

轨道

  'id'    'title'        'album_id'
   1      Track 1       1
   2      Track 2       1
   3      Track 3       2
   4      Track 4       2

资产

'id'  'track_id'
 1      1
 2      1
 3      2
 4      2
 5      3
 6      3
 7      4

所以我的查询 o/p 应该是

'id'    'name'
  1      Album 1

AsAlbum 1 有两个音轨Track 1Track 2并且这两个2 assets音轨Track 4Album 2只有1 asset

4

1 回答 1

4

尝试:

SELECT    a.id,
          a.name
FROM      albums a
JOIN      tracks b ON a.id = b.album_id
LEFT JOIN (
          SELECT   track_id
          FROM     assets
          GROUP BY track_id
          HAVING   COUNT(*) >= 2
          ) c ON b.id = c.track_id
GROUP BY  a.id, 
          a.name
HAVING    COUNT(*) = COUNT(c.track_id)

SQLFiddle 演示

于 2012-08-13T09:06:34.370 回答