【发布时间】:2011-10-05 22:42:45
【问题描述】:
我有三个表:students、interests 和 interest_lookup。
Students 有学生 ID 和姓名列。
Interests 具有兴趣 ID 和兴趣名称这两个列。
Interest_lookup 有两个 cols student_id 和 interest_id。
要了解学生的兴趣所在
select interests.interest_name from `students`
inner join `interest_lookup`
on interest_lookup.student_id = students.student_id
inner join `interests`
on interests.interest_id = interest_lookup.interest_id
我想做的是得到一个类似的结果集
student_id | students.name | interest_a | interest_b | ...
列名“interest_a”是interests.name 中的一个值,并且 interest_ 列是 0 或 1,因此当值是 1 给定的interest_lookup 中有记录 student_id 和interest_id 没有时为0。
兴趣表中的每个条目都必须显示为列名。
我可以通过子选择(这非常慢)或进行一堆连接来做到这一点,但这两者都需要我首先从兴趣中选择所有记录并写出一个动态查询。
【问题讨论】:
-
我能想到的唯一方法是使用关键技术,但这也需要提前知道
interest_name的所有值