我有三张桌子:
Student: id,name
Lesson: id,name
Student_Lesson: student_id, lesson_id
我想创建一个查询,例如:
Select s.name as student_name,
(
Select l.name
from Lesson as l
inner join Student_Lesson as sl on sl.lesson_id=l.id
where sl.student_id=s.id
) as lessons
from Student as s where <Complex query>
这给出了错误:
子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。
正如预期的那样,因为学生附上了多个课程,我可以连接所有结果并得到如下结果:
_____________________________________________
| student_name | lessons |
| ----------------|-------------------------|
| Luke Skywalker | Physics,Chemistry |
| Han Solo | Mathematics,Physics |
|_________________|_________________________|
如果我将所有学生的课程数减少到1,这个查询就可以了。
可能存在语法错误,因为我重构了我的查询,我可能犯了一些错误。
答案 0 :(得分:2)
使用XML PATH:
create table #student (
id int identity(1,1),
name varchar(100)
)
create table #lesson (
id int identity(1,1),
name varchar(100)
)
create table #student_lesson (
student_id int,
lesson_id int
)
insert into #student values
('Luke Skywalker'), ('Han Solo')
insert into #lesson values
('Chemistry'), ('Mathematics'), ('Physics')
insert into #student_lesson values
(1, 3), (1, 1), (2, 2), (2, 3)
select
student_name = s.name,
lessons = stuff((
select ', ' + name
from #lesson t
inner join #student_lesson t2
on t.id = t2.lesson_id
where t2.student_id = s.id
group by t.name
for xml path(''), type).value('.', 'varchar(max)')
, 1, 2, '')
from #student s
drop table #student
drop table #lesson
drop table #student_lesson