mysql - 创建基于多列值计算总值的 View 表

标签 mysql view

这些是我的示例表 类(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/

相关文章:

android - GridView getChildAt() 返回 null

android - 重绘 View Android

android - 在 Android View 上哪里可以正确释放位图?

php - 从多个表中抓取信息

PHP MySQL - 在 <Select></select> 表单上显示值

mysql - SQL - 带有优先级过滤器的 SELECT 查询

python - 禁用 Django 中所有表单字段的语法

mysql - 从每个 "group"中仅选择一个

php - 生成我自己的 Eloquent 模型插入 ID - 如何避免 PK 冲突?

postgresql - Postgres 可编辑联合 View