即使id不存在,Mysql也会获取所有带有学生姓名的主题

标签 mysql sql

我有以下数据库结构:

学生表

      id name gender
       1  abc  male
       2  xyz  female

科目表

       id  name
        1  maths
        2  science
        3  english

学生成绩

      id st_id  sub_id marks
       1   1       1    20
       2   1       2    30
       3   2       1    40

我想要这样的结果:

      name  subjects  marks 
       abc    maths     20
       abc    science   30  
       xyz     maths    40
       abc     english  0
       xyz     science  0
       xyz      english 0

单独使用MySQL查询是否可以达到上述结果?


我试过这个查询:

SELECT * 
FROM students 
LEFT JOIN studentmarks 
    ON studentmarks.std_id = students.id 
LEFT JOIN subjects 
    ON subjects.id = studentmarks.sub_id

结果不是我想要的,因为我正在使用join 所以它只会返回匹配的id

最佳答案

这可能有效

SELECT cr.st_name, cr.sub_name, COALESCE(c.marks, 0) 
FROM (SELECT a.id   st_id, 
             a.NAME st_name, 
             b.NAME sub_name, 
             b.id   sub_id 
        FROM students a, 
             subjects b) cr 
LEFT JOIN studentmarks c
    ON cr.sub_id = c.sub_id 
    AND c.st_id = cr.st_id 

关于即使id不存在,Mysql也会获取所有带有学生姓名的主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48212390/

相关文章:

php - 如何在 'while' 表生成期间检查 MySQL 结果

php - 查询连接三个表 yii

mysql - SQL - 从 JOIN 查询中选择不同的 AND 计数

sql - 存储过程位参数激活附加 where 子句以检查空值

sql - 如何将 Reporting Services 多值参数发送到 SQL Server 函数?

php - UTF-8贯穿始终

mysql - SQL 加入计数

php - 我可以在 PHP 中混合使用 MySQL API 吗?

sql - 如何在 SQL 中拆分数据

mysql - 聚合函数上的 RANK OVER PARTITION BY