加入两个表以生成给定的输出

时间:2016-12-07 06:21:36

标签: mysql

describe user;

 id       int(1)       NO    'PRI'  0             
 name     'varchar'(20)  YES        NULL           
 address  'varchar'(20)  YES        NULL          
 class    int(2)       YES        NULL           
 DOB      date         YES        NULL           
 created  date         YES        NULL 


describe 'marklist'
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| id          | int(1)      | NO   |     | 0       |       |
| subject     | varchar(10) | YES  |     | NULL    |       |
| 'markscored'| int(2)      | YES  |     | NULL    |       |
| 'outof'     | int(2)      | YES  |     | NULL    |       |
| 'userid'    | int(2)      | YES  |'NUL'| NULL    |       |
+-------------+-------------+------+-----+---------+-------+

这是给出的两个表,从这两个表中我需要输出为:

|name |class|biology|chemistry|physics|outoftotal|totalmarkscored|percentage|
+-----+-----+-------+---------+-------+----------+---------------+----------+
|arun | 5   |  45   |  42     |  40   |  150     | 127           |84.6      |

请使用两个表user和marklist'

给我一​​个查询以获得上述输出

2 个答案:

答案 0 :(得分:0)

顺便说一句,int(2)有' 150'这很奇怪。

'用户'在sql中也是一个保留字,所以不要使用它pls

SELECT u.name,u.class,
(SELECT SUM(subject) FROM marklist WHERE subject LIKE 'biology') AS biology,
(SELECT SUM(subject) FROM marklist WHERE subject LIKE 'chemistry') AS chemistry,m.outof AS outoftotal,m.markscored AS     
totalmarkscored,m.markscored/m.outof*100
FROM user u, marklist m
WHERE u.id=m.id

答案 1 :(得分:0)

在执行修改后的查询后感谢MVCNoob:  SELECT u.id,u.name,u.class,  (SELECT SUM(markscored)FROM marklist WHERE subject LIKE' biology' AND u.id = m.id)AS biology,  (SELECT SUM(markscored)FROM marklist WHERE subject LIKE' chemistry' AND u.id = m.id)AS chemistry,  (SELECT SUM(markscored)FROM marklist WHERE subject LIKE' physics' AND u.id = m.id)AS physics,  (SELECT SUM(markscored)FROM marklist WHERE u.id = m.id)AS total,  (SELECT SUM(outof)FROM marklist WHERE u.id = m.id)AS outof,  ((SELECT SUM(markscored)FROM marklist WHERE u.id = m.id)/(SELECT SUM(outof)FROM marklist WHERE u.id = m.id)* 100)as p  来自你,marklist m  WHERE u.id = m.userid = 1; ,我得到一个输出: + ------ + ------ + ------- + --------- + ----------- + ----- ---- + ------- ------- + + --------- + | id |名字|班级|生物学|化学|物理|总计| outof | p | + ------ + ------ + ------- + --------- + ----------- + ----- ---- + ------- ------- + + --------- + | 1 |阿伦| 6 | 37 | 48 | 48 | 133 | 150 | 88.6667 | | 1 |阿伦| 6 | NULL | NULL | NULL | NULL | NULL | NULL | | 1 |阿伦| 6 | NULL | NULL | NULL | NULL | NULL | NULL | + ------ + ------ + ------- + --------- + ----------- + ----- ---- + ------- ------- + + --------- + 集合中的3行(0.00秒),这里arun正在重复pls请让我查询以避免重复 感谢你