检索列的总和大于不同表的其他列的行

时间:2013-07-24 04:59:30

标签: mysql sql mysqli sum

我有两个数据库表。

第一张表:

| ID  |  Sub-Name |  Marks
| 01  |  french   |  50
| 01  |  russian  |  50
| 02  |  french   |  30
| 02  |  russian  |  50
| 03  |  french   |  20
| 03  |  russian  |  30

第二张表:

|  ID | Stu-name | passing_marks
|  01 | abc      | 90
|  02 | xyz      | 90
|  03 | mno      | 90

我想得到法语和俄语的集体商标比表2的passing_marks更高的学生的名字。

2 个答案:

答案 0 :(得分:3)

请首先声明primarykeyforeignkey与表格的关系table name

这里我将第一个命名为detail,第二个表名为student

SELECT student.ID, student.Stu_name, detail.collective
FROM student
JOIN  
(
   SELECT ID, SUM(Marks) AS collective
   FROM detail GROUP BY ID
) detail
ON student.ID = detail.ID
AND detail.collective> student.passing_marks;

答案 1 :(得分:0)

尝试加入子查询,如下所示:

SELECT t2.ID, t2.Stu_name, t1.Total 
FROM Table2 t2
JOIN  
(
   SELECT ID, SUM(Marks) AS Total
   FROM Table1 GROUP BY ID
) t1
ON t2.ID = t1.ID
AND t1.Total > t2.passing_marks;

输出:

| ID | STU_NAME | TOTAL |
-------------------------
|  1 |      abc |   100 |

请参阅this SQLFiddle