How to transpose rows and columns of a database

Source: Internet
Author: User
How to change the rows and columns of a database to thinkphp and mysql. Database:

The SQL statement for table creation is as follows:
CREATE TABLE `score_collect` (   `std_id` int(10) NOT NULL,   `course_id` int(11) 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');


You need to adjust the data in to be displayed in the foreground as follows:

The number of table rows is not fixed. Std_id and course_id are also not fixed.
(I do not know if I have clearly expressed the problem ). You can also use php, but I think it is best to use SQL statements. Of course .. Best Performance.
Sorry, thank you.
In addition, I wish you a happy spring festival and all the best. 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(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 $key1=>$val1){$list[$key][$val1]=$score_arr[$key1];}}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.