【问题标题】:How to join 2 tables and show all first table even second table where clause not met? [duplicate]如何连接 2 个表并显示所有第一个表甚至第二个表 where 子句不满足? [复制]
【发布时间】:2018-07-25 06:26:53
【问题描述】:

我想做简单的上学/出席,想法是老师应该每天决定学生的出席状态。

我有 2 张桌子,学生和出席

这是学生表

这里是存在表

现在我想在我的网站上创建一个界面,通过 class_name 和 date_presence 显示所有学生。

如果班级和当前日期的所有学生都没有出席状态,则显示所有出席状态为“尚未决定”的学生

如果班级和当前日期的某个学生没有在场状态,那么它会为已经设置了在场状态的学生显示学生在场状态 A/I/S,而另一个学生则显示为“尚未决定”

这是我的查询

SELECT `a`.`student_id`, `a`.`student_name`, `b`.`presence_id`, `b`.`presence_status`, `b`.`date_presence` 
FROM `student` `a` 
left JOIN `presence` `b` ON `a`.`student_id` = `b`.`student_id` 
WHERE `a`.`class_name` = 'KLJ0009' and `b`.`date_presence` = '2018-07-24'

这是结果

它只显示 3 个人,我想要显示所有学生,其 class_name 是 KLJ0009,如果学生没有出席状态,则显示出席 ID、出席状态和日期出席为空

我该怎么做?

提前致谢。

【问题讨论】:

  • 如果您将示例数据包含为文本而不是图像,您会得到更快的答案。

标签: mysql


【解决方案1】:

您需要将以下条件移至查询的ON 部分:

`b`.`date_presence` = '2018-07-24'

所以您的查询如下所示:

SELECT `a`.`student_id`, `a`.`student_name`, `b`.`presence_id`, `b`.`presence_status`, `b`.`date_presence` 
FROM `student` `a` LEFT JOIN `presence` `b` ON `a`.`student_id` = `b`.`student_id` AND `b`.`date_presence` = '2018-07-24'
WHERE `a`.`class_name` = 'KLJ0009'

注意:如果您想始终查询当前日期,可以使用NOWCURDATE 而不是2018-07-24

演示: https://www.db-fiddle.com/f/762aXDfQConnR8XbwYQ3z4/0

【讨论】:

    【解决方案2】:

    您需要当前日期,因此请使用 now() 函数和 case when 获取状态

    SELECT `a`.`student_id`, `a`.`student_name`, `b`.`presence_id`,
    case when `b`.`presence_status` is not null then `b`.`presence_status` else 'Yet not Decided' as  presence_status, `b`.`date_presence` FROM `student` 
    `a` left JOIN `presence` `b` 
     ON `a`.`student_id` = `b`.`student_id` 
     and  `b`.`date_presence` = date(now())
     WHERE `a`.`class_name` = 'KLJ0009' 
    

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      相关资源
      最近更新 更多