我的桌子是
table1是
class_name subject_Name
I class telugu
I class hindi
II class telugu
II class hinditable2是
exam_name telugu hindi
unit 1 25 35
unit 2 30 35现在,我在table1中插入一行,subject maths.That subject作为列添加到table2中,并检查主题(数学)是否存在于table2中。
我需要的输出是
table1是
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 mathstable2是
exam_name telugu hindi maths
unit 1 25 35 35
unit 2 30 35 25提前谢谢..。
发布于 2013-07-16 15:40:21
我将调整表2以使其规范化,使用以下列:
exam_name,主语,得分
使用主键exam_name,subject
然后你就可以查询它,得到不同科目的所有分数。
表:
mysql> SELECT * FROM t2;
+-----------+---------+-------+
| exam_name | subject | score |
+-----------+---------+-------+
| unit1 | hindi | 25 |
| unit1 | telugu | 45 |
| unit2 | math | 15 |
| unit2 | telugu | 25 |
+-----------+---------+-------+现在您可以查询:首先,您需要找出所有的主题:
SELECT DISTINCT subject from t2;现在,您可以使用主题创建一个枢轴表:
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组合只有一个条目。
您可以将这两个步骤组合在一个复杂的查询中。取决于您是否从脚本中调用它,这可能更好,也可能不可取。
https://stackoverflow.com/questions/17680926
复制相似问题