我有2张桌子,其中一张(让我们称之为'曲目')将有音乐曲目信息,如标题,时间,样本文件,价格和所需的所有内容。第二个表格(让我们称之为'类别')将具有来自第一个表格的类型,类别类型(工具,流派,情绪等)和类别ID。
特定曲目可能有未知数量的类别。例如,id = 1的曲目可以有乐器类别3和4,情绪类别1,2,3等等。
我需要获得可分类(按标题,时间,价格或其他)的曲目列表,这些曲目也使用LIMIT(用于分页)按心情或乐器或任何类型过滤。
任何人都可以帮我组装这样的查询吗?我不知道如何开始。
以下是表结构示例:
表'曲目'
+----+---------+-------+------+
| id | title | Price | Time |
+----+---------+-------+------+
| 1 | Title 1 | 10 | 0 |
| 2 | Title 2 | 9 | 1 |
| 3 | Title 3 | 8 | 2 |
+----+---------+-------+------+
表'类别'
+----+------------+-------------+----------+
| id | type | category_id | track_id |
+----+------------+-------------+----------+
| 1 | instrument | 1 | 1 |
| 2 | instrument | 10 | 1 |
| 3 | genre | 1 | 1 |
| 4 | mood | 15 | 2 |
+----+------------+-------------+----------+
我当然会使用int作为类别类型,但我以单词为例。
关于致命缺陷的更新:
juergen d解决方案效果很好,但它有一个致命的缺陷。如果我在单独的下拉列表中拥有所有可能的乐器,流派和情绪,我想通过选择下拉框来过滤出具有乐器1,情绪2和流派3的曲目。该列表显示所有具有乐器1或情绪2或......不是AND的曲目。有人可以帮我修改吗?
答案 0 :(得分:4)
更好的数据库设计
表'曲目'
+----+---------+-------+------+
| id | title | Price | Time |
+----+---------+-------+------+
| 1 | Title 1 | 10 | 0 |
| 2 | Title 2 | 9 | 1 |
| 3 | Title 3 | 8 | 2 |
+----+---------+-------+------+
表'类别'
+----+------------+
| id | type |
+----+------------+
| 1 | instrument |
| 2 | genre |
| 3 | mood |
+----+------------+
表' track_categories'
+-------------+-------------------------+
| category_id | sub_category | track_id |
+-------------+-------------------------+
| 1 | 3 | 1 |
| 1 | 1 | 1 |
| 3 | 1 | 1 |
| 2 | 3 | 2 |
+-------------+-------------------------+
然后你可以运行查询(例如类型曲目)
select t.*
from tracks t
join track_categories tc on tc.track_id = t.id
join categories c on c.id = tc.category_id
where c.type = 'genre'
如果您想选择具有特定类型组合的曲目,请使用
select t.title
from tracks t
join track_categories tc on tc.track_id = t.id
join categories c on c.id = tc.category_id
group by t.title
having sum(c.type = 'instrument' and tc.sub_category = 1) > 0
and sum(c.type = 'mood' and tc.sub_category = 2) > 0
and sum(c.type = 'genre' and tc.sub_category = 3) > 0