这些是我的示例表 类(class)表包括
course_id | course name 1 | java 2 | .net 3 | php 4 | ruby and rails
Indian_student table include
course_id | no.of student 2 | 10 3 | 30
Japan_student table include
course_id | no.of student 1 | 50 2 | 30
Chinese_student table include
course_id | no.of student 2 | 60 4 | 20
I want the output as
Course_id | in_stu | ja_stu | ch_stu | total 1 | 0 | 50 | 0 | 50 2 | 10 | 30 | 60 | 100 3 | 30 | 0 | 0 | 30 4 | 0 | 0 | 20 |20
But I only get the result
Course_id | in_stu | ja_stu | ch_stu | total 2 | 10 | 30 | 60 | 100
my view is
create view total_student as select
i.indian_stu as in_stu,
j.japan_stu as ja_stu,
c.chinese_stu as ch_stu,
main.course_id as course_id,
(i.indian_stu + j.japan_stu + c.chinese_stu) as total
from indian_student i, japan_student j,chinese_student c, course c
where i.course_id=main.course_id and j.course_id=main.course_id and c.course_id=main.course_id group by course_id;
请给我一些建议
最佳答案
您正在使用 20 世纪 90 年代的老式方法将表连接在一起:以逗号分隔的表列表。这不足以完成您的任务。您需要 LEFT JOIN ,因为逗号语法是 INNER JOIN 语法。 INNER JOIN
忽略不匹配的行。
(此外,您的示例查询使用 c
别名两次;这是行不通的。它还使用 GROUP BY
但我相信您想要 ORDER BY
)
你想要这个:
select i.indian_stu as in_stu,
j.japan_stu as ja_stu,
x.chinese_stu as ch_stu,
main.course_id as course_id,
(i.indian_stu + j.japan_stu + c.chinese_stu) as total
from course c
left join indian_student i ON c.course_id = i.course_id
left join japan_student j ON c.course_id = j.course_id
left join chinese_student x on c.course_id = x.course_id
order by c.course_id
当您开发 View 时,首先让 SELECT 语句起作用,然后使用它来创建 View 。这比不断删除并重新创建 View 更容易。
关于mysql - 创建基于多列值计算总值的 View 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491055/