MYSQL列中的多个值

时间:2017-09-25 03:09:51

标签: mysql sql

所以我现在有三个数据库。这是生成每个表的SQL代码。

CREATE TABLE `Course` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(25) NOT NULL,
    `startTime` time NOT NULL,
    PRIMARY KEY (`id`)
);

CREATE TABLE `School` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `schoolname` varchar(25) NOT NULL,
    PRIMARY KEY (`id`)
);

CREATE TABLE `SchoolCourse` (
    `schoolid` int(11) NOT NULL,
    `courseid` int(11) NOT NULL,
    PRIMARY KEY (`schoolid`,`courseid`),
    KEY `FK_course` (`courseid`),
    CONSTRAINT `FK_course` FOREIGN KEY (`courseid`) REFERENCES `Course` (`id`),
    CONSTRAINT `FK_Student` FOREIGN KEY (`schoolid`) REFERENCES `School` (`id`)
);

我对这些表的目标是让它看起来像这样

---------------------------------------------------
|School Name  |          Courses                  |
---------------------------------------------------
| School1     | Course1, Course2, Course3         |
| School2     | Course1, Course3                  |
| School3     | Course3                           |
| School4     | Couse1, Course2, Course3, Course4 |
---------------------------------------------------

我似乎无法弄清楚如何做到这一点。我尝试输入这样的值。

INSERT INTO 'ShcoolCourse' VALUES (
(1, 1), (1, 2), (1, 3),
(2, 1), (2, 3),
(3, 3),
(4, 1), (4, 2), (4, 3), (4, 4)); 

然后从那里我会执行连接并尝试将值放入一列但到目前为止没有运气, 我已经环顾了其他问题,其中一些人有同样的想法,但不完全是我的意思 这样做。任何帮助都会得到极大的赞赏。

2 个答案:

答案 0 :(得分:2)

您当前的架构已规范化并且完全正常。如果您想要这样的逗号分隔输出,那么只需在使用GROUP_CONCAT查询时生成它:

SELECT
    t1.id,
    t1.schoolname AS `School Name`,
    GROUP_CONCAT(t3.name) AS Courses
FROM School t1
LEFT JOIN SchoolCourse t2
    ON t1.id = t2.schoolid
LEFT JOIN Course t3
    ON t2.courseid = t3.id
GROUP BY
    t1.id,
    t1.schoolname

请注意,我在汇总中同时包含idschoolname,因为两个不同的学校可能巧合地使用相同的名称,我们需要一些方法来区分它们。

答案 1 :(得分:1)

您可以将GROUP BYgroup_concat

一起使用
select
    s.schoolname `School Name`,
    group_concat(c.name) Courses
from school s
left join schoolcourse sc on s.id = sc.schoolid
left join cource c on c.id = sc.courseid
group by s.id