How to do the database row and column transpose

Source: Internet
Author: User
thinkphp and MySQL. Database:

The SQL statement that builds the table is as follows:
CREATE TABLE ' score_collect ' (   ' std_id ' int () not null,   ' course_id ' int (one) not NULL,   ' score ' varchar (255) DEFAULT NULL,   PRIMARY KEY (' std_id ', ' course_id '),)

INSERT into ' score_collect ' VALUES (' 2012508082 ', ' 2 ', ' 20 '); INSERT into ' score_collect ' VALUES (' 2012508082 ', ' 3 ', ' 10 '); INSERT into ' score_collect ' VALUES (' 2012508082 ', ' 4 ', ' 30 '); INSERT into ' score_collect ' VALUES (' 2012508084 ', ' 2 ', ' 21 '); INSERT into ' score_collect ' VALUES (' 2012508084 ', ' 3 ', ' 11 '); INSERT into ' score_collect ' VALUES (' 2012508084 ', ' 4 ', ' 31 ');


What needs to be done is to adjust the data in the foreground so that it shows up:

Where the number of table rows is not fixed. STD_ID and course_id are also not fixed.
(I don't know if I have a clear question). PHP is OK, but I think it's best to use the SQL statement. Of course.. It is best to combine performance.
Kneel down and beg the great God to solve, thank you.
In addition I wish you a happy Spring Festival and good luck. Thank you


Reply to discussion (solution)

SELECT Std_id,group_concat (course_id) as Course_id,group_concat (score) as score from ' Score_collect ' GROUP by std_id;

$list =array (The array (' std_id ' = ' 2012508082 ', ' course_id ' = ' 2,3,4 ', ' score ' = ' 20,10,30 '), Array (' std_id ' = > ' 2012508084 ', ' course_id ' = ' 2,3,4 ', ' score ' = ' 21,11,31 '), foreach ($list as $key = $val) {$course _id_ Arr=explode (', ', $val [' course_id ']), $score _arr=explode (', ', $val [' score ']), unset ($list [$key] [' course_id ']); unset ($list [$key] [' score ']); foreach ($course _id_arr as $key 1=> $val 1) {$list [$key] [$val 1]= $score _arr[$key 1];}} Print_r ($list);
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.