Error al ejecutar consulta(1242):子查询返回超过1行

时间:2017-10-23 02:41:25

标签: mysql function

BEGIN
   DECLARE hola VARCHAR(255);
   SET hola = (SELECT codigo FROM estudiante WHERE semestre = prmSemestre);
   RETURN hola;
END

Problem Img

我怎样才能解决它?

1 个答案:

答案 0 :(得分:0)

如果你想要这样的东西

+----------+------+----------------------+
| SudentID | Name | courses              |
+----------+------+----------------------+
|        1 | abc  | 1 Geog,2 Hist,3 Chem |
|        2 | def  | 2 Hist               |
|        3 | ghi  | 2 Hist,3 Chem        |
+----------+------+----------------------+
3 rows in set (0.00 sec)

你的模型看起来像这样

ariaDB [sandbox]> select sudentid,name from student where sudentid < 4;
+----------+------+
| sudentid | name |
+----------+------+
|        1 | abc  |
|        2 | def  |
|        3 | ghi  |
+----------+------+
3 rows in set (0.00 sec)

MariaDB [sandbox]> select * from courses;
+------+------+
| ID   | NAME |
+------+------+
|    1 | Geog |
|    2 | Hist |
|    3 | Chem |
+------+------+
3 rows in set (0.00 sec)

MariaDB [sandbox]> select * from studentcourses;
+------+------+
| Sid  | Cid  |
+------+------+
|    1 |    1 |
|    1 |    2 |
|    1 |    3 |
|    2 |    2 |
|    3 |    2 |
|    3 |    3 |
+------+------+
6 rows in set (0.00 sec)

然后group_concat会做

select s.SudentID,s.Name,
        (select group_concat(c.id,' ',c.name) from StudentCourses sc join Courses c on sc.cid = c.id 
        where sc.sid = s.sudentid
        group by sc.sid) courses
from student s
where sudentid < 4
;