mysql - 在 MySQL 中动态地将行转换为列

标签 mysql sql yii pivot

我在使用 MySQL 时遇到问题。我想要基于行的动态列。这是详细信息

SELECT `marks`.`id` , `marks`.`studentID` , `marks`.`subjectID` , `marks`.`mark`
FROM `Mark` `marks`
LEFT OUTER JOIN `Student` `students` ON ( `students`.`id` = `marks`.`studentID` )
WHERE (
`students`.`classID` =1
)
LIMIT 0 , 30

My Output is 
+----+-----------+-----------+------+
| id | studentID | subjectID | mark |
+----+-----------+-----------+------+
|  1 |         1 |         1 |   20 |
|  2 |         1 |         2 |   36 |
|  3 |         2 |         1 |   47 |
|  4 |         2 |         2 |   43 |
+----+-----------+-----------+------+
4 rows in set (0.00 sec)


Output I need is 

+----+-----------+-----------+-----------+
| id | studentID | subject_1 | subject_2 |
+----+-----------+-----------+-----------+
|  1 |         1 |        20 |        36 |
|  2 |         2 |        47 |        43 |
+----+-----------+-----------+-----------+
4 rows in set (0.00 sec)

主题的数量取决于主题表中的条目。每个用户只需要一行来显示所有标记。这是我使用的表结构。

--
-- Table structure for table `Mark`
--

CREATE TABLE IF NOT EXISTS `Mark` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `studentID` int(11) NOT NULL,
  `subjectID` int(11) NOT NULL,
  `mark` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

--
-- Table structure for table `Student`
--

CREATE TABLE IF NOT EXISTS `Student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `classID` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

--
-- Table structure for table `Subject`
--

CREATE TABLE IF NOT EXISTS `Subject` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

提前致谢

最佳答案

您不能拥有动态列,至少不能动态生成 SQL。您可以按照此答案在存储过程中构建 SQL

MySQL pivot table query with dynamic columns

或者,在您的应用程序代码中执行此操作可能更简单,方法是在一个查询中选择不同的主题,然后使用该结果集构建 SQL 来检索您想要的结果集。至少通过应用程序代码中的逻辑,您对结果集中将看到多少列有所了解。

关于mysql - 在 MySQL 中动态地将行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20579772/

相关文章:

mysql - 平均维修间隔时间(按单位)

php - WAMP 和 mysqli::real_connect(): (HY000/2002)?

sql - 如果存在多个表的记录,如何返回 bool 值

php - Yii 文件上传 $_FILE 为空

Yii 按另一个表 CActiveDataProvider 排序

php - Yii2 - 如何从 Yii::$app->user 获取当前用户名或名称?

python - Django ORM : Dynamically determine another table name according one field value

mysql - 关于优化MySQL查询: Simple MySQL query takes more than 3 seconds

sql - 从动态 sql 中选择非空列作为逗号分隔的字符串

MySQL获取两个字符串字段之间的差异