首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在另一个表中插入一行时添加列

在另一个表中插入一行时添加列
EN

Stack Overflow用户
提问于 2013-07-16 15:35:46
回答 1查看 187关注 0票数 0

我的桌子是

table1是

代码语言:javascript
复制
         class_name    subject_Name

              I class         telugu
              I class          hindi
              II class         telugu
              II class          hindi

table2是

代码语言:javascript
复制
         exam_name    telugu   hindi

            unit 1      25      35
            unit 2      30      35

现在,我在table1中插入一行,subject maths.That subject作为列添加到table2中,并检查主题(数学)是否存在于table2中。

我需要的输出是

table1是

代码语言:javascript
复制
         class_name    subject_Name

              I class         telugu
              I class          hindi
              II class         telugu
              II class          hindi
              II class         maths
              III class          hindi
              III class         telugu
              III class          maths

table2是

代码语言:javascript
复制
         exam_name    telugu   hindi  maths

            unit 1      25      35     35
            unit 2      30      35      25

提前谢谢..。

EN

回答 1

Stack Overflow用户

发布于 2013-07-16 15:40:21

我将调整表2以使其规范化,使用以下列:

exam_name,主语,得分

使用主键exam_name,subject

然后你就可以查询它,得到不同科目的所有分数。

表:

代码语言:javascript
复制
mysql> SELECT * FROM t2;
+-----------+---------+-------+
| exam_name | subject | score |
+-----------+---------+-------+
| unit1     | hindi   |    25 |
| unit1     | telugu  |    45 |
| unit2     | math    |    15 |
| unit2     | telugu  |    25 |
+-----------+---------+-------+

现在您可以查询:首先,您需要找出所有的主题:

代码语言:javascript
复制
SELECT DISTINCT subject from t2;

现在,您可以使用主题创建一个枢轴表:

代码语言:javascript
复制
SELECT exam_name, details.hindi, details.telugu, details.math 
FROM (
   SELECT exam_name, 
          SUM(if(subject='hindi',score,0)) AS hindi, 
          SUM(if(subject='telugu', score, 0)) AS telugu, 
          SUM(if(subject='math', score, 0)) AS math 
   FROM t2 GROUP BY exam_name

) AS details ;

+-----------+-------+--------+------+
| exam_name | hindi | telugu | math |
+-----------+-------+--------+------+
| unit1     |    25 |     45 |    0 |
| unit2     |     0 |     25 |   15 |
+-----------+-------+--------+------+

查阅枢轴表以获得更详细的信息。此解决方案假定表中的每个that _name/subject组合只有一个条目。

您可以将这两个步骤组合在一个复杂的查询中。取决于您是否从脚本中调用它,这可能更好,也可能不可取。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17680926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档