简体   繁体   中英

How to add a new column to a table in mysql by query

I have a table in Mysql like this:

studetname  Course
jon          C1
David        C2
wayne        C3
jon          C3

I need to result be in a table like this:

studentname    Course1 Course2 
jon            C1       C3
David          C2
wayne          C3

It would be appreciated if any help me. Thanks

If you need only all the result for each student on a rows you could use a group_concat eg:

SELECT studentname, group_concat(course) AS Courses
FROM my_table
GROUP BY studentname

You can add the column with the following statement:

ALTER TABLE my_table ADD COLUMN Course2 CHAR(2)

Where my_table is the name of your table and CHAR(2) is the type of the column (you will probably want the same as Course1 )

Have a look at the docs .

But doing it that way is totally wrong!

You are mixing concepts in your tables, what happens when a student enrolls for a third course? Or a fourth?

If your table is a junction table, see the answer posted by @scaisEdge.

Otherwise, if you are trying to store all the student information in one table, you should change the structure of your database to have:

A student table that stores student information, for example:

table student
  id  |    name    |      email       
  1   |  aragorn   |   aragorn@lotr.me
  2   |  gandalf   |   gandalf@lotr.me
...

Another table to store course information:

table course
  id  |      name    |    ....
  1   |     magic1   |    ....
  2   | swordmanship |    ....

And a junction table to store which students are enrolled in which courses:

table student_course
student_id    |    course_id
    1         |        1       // Gandalf is taking magic1
    2         |        2       // Aragorn is taking swordmanship
    1         |        2       // But Gandalf also is taking swordmanship

In this junction table student_id would be a foreign key to student.id and course_id a foreign key to course.id .

There is some good introductory information about the relational model in wikipedia .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM