怎么做数据库的行列转置?

WBOY
Release: 2016-06-13 12:15:59
Original
1115 people have browsed it

如何做数据库的行列转置??
thinkphp和mysql。数据库如图所示:

建表的sql语句如下:

<br />CREATE TABLE `score_collect` (<br />   `std_id` int(10) NOT NULL,<br />   `course_id` int(11) NOT NULL,<br />   `score` varchar(255) DEFAULT NULL,<br />   PRIMARY KEY (`std_id`,`course_id`),<br /> )<br />
Copy after login

<br />INSERT INTO `score_collect` VALUES ('2012508082', '2', '20');<br /> INSERT INTO `score_collect` VALUES ('2012508082', '3', '10');<br /> INSERT INTO `score_collect` VALUES ('2012508082', '4', '30');<br /> INSERT INTO `score_collect` VALUES ('2012508084', '2', '21');<br /> INSERT INTO `score_collect` VALUES ('2012508084', '3', '11');<br /> INSERT INTO `score_collect` VALUES ('2012508084', '4', '31');<br />
Copy after login


需要实现的是将上图中的数据调整为这样在前台显示出来:

其中,表行数不固定。std_id和course_id也不固定。
(不知道我把问题表达清楚了没有)。用php也可以,但是我想最好还是用sql语句吧。当然。。能兼顾性能最好。
跪求各路大神解决,谢谢。
另外祝大家春节快乐,万事如意。 谢谢
------解决思路----------------------
<br />SELECT std_id,GROUP_CONCAT(course_id) AS course_id,GROUP_CONCAT(score) AS score FROM `score_collect` GROUP BY std_id;<br />
Copy after login

<br />//$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'),);<br /><br />foreach($list as $key=>$val)<br />{<br />	$course_id_arr=explode(',',$val['course_id']);<br />	$score_arr=explode(',',$val['score']);<br />	unset($list[$key]['course_id']);<br />	unset($list[$key]['score']);<br />	foreach($course_id_arr as $key1=>$val1)<br />	{<br />		$list[$key][$val1]=$score_arr[$key1];<br />	}<br />}<br /><br />print_r($list);<br />
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!