在带有时间戳列的Postgresql上联合加入

时间:2019-06-23 03:59:01

标签: sql postgresql

这是一个简单的查询,可在特定日期获取学生的出勤行。

条件 1.如果该日期有学生出席,请参加 2.如果不只是检索学生栏

我的查询看起来像

Select 0 as attendanceId, 0 as attendanceVersion, '' as inTime,'' as 
outTime,'' as summary,Student.id As 
StudentId,Student.firstName,Student.lastName 
From  Student where student.id not in 
    ( Select student.id From Student join Attendance on ( student.id = 
      Attendance.studentId )
      where  attendance.inactiveDate is null and student.inactivedate is 
      null and 
      date(attendance.intime) = '2019-06-23' )
and student.inactivedate is null  

UNION

Select Attendance.id As AttendanceId,Attendance.version,Attendance.inTime,Attendance.outTime,Attendance.summary,
Student.id As StudentId,Student.firstName,Student.lastName 
From Student join Attendance on ( student.id = Attendance.studentId ) where  
attendance.inactiveDate is null and student.inactivedate is null and 
date(attendance.intime) = '2019-06-23' 
order by student.firstname, student.id 

我正在尝试做的事情: 选择没有出勤的学生行,然后将其与有出勤的学生行合并。

问题: 出现以下错误

错误:带有时区:“”的时间戳类型的输入语法无效

SQL状态:22007

字符:51

我希望Postgres可以用空文字代替时区。如何用空字符串替换时区或执行此查询的更好方法

更新:

Select 
Attendance.id As AttendanceId,Attendance.version, Attendance.inTime,Attendance.outTime,Attendance.summary,
Student.id As StudentId,Student.firstName,Student.lastName 
From Student left join Attendance on ( student.id = Attendance.studentId ) 
where student.inactivedate is null and date(attendance.intime) = '2019-06-23' 
order by student.firstname, student.id

产生单行,如内部联接。猜猜是因为我要参加Studentid吗?!

8;1;"2019-06-23 08:55:11+05:30";"";"";16;"AADITH";"PRASAD"

2 个答案:

答案 0 :(得分:2)

每次在where子句中使用左联接列时,查询都会转换为内部联接:

SELECT * FROM
  lef 
  LEFT JOIN
  ri 
  ON lef.id = ri.id
WHERE ri.column = 'some value'

此查询将像内部查询一样工作;左联接将在ri中没有匹配项的任何行中放入空值,但是where子句将取出空值,因为它们都不可以等于“某个值”

空值永远不会等于任何东西

要解决此问题,请将谓词置于连接条件中:

SELECT * FROM
  lef 
  LEFT JOIN
  ri 
  ON lef.id = ri.id AND ri.column = 'some value'

开始查询:

Select 
  a.id As AttendanceId,
  a.version,     
  a.inTime,
  a.outTime,
  a.summary,
  s.id As StudentId,
  s.firstName,
  s.lastName 
From 
  Student s 
  left join 
  Attendance a
  on 
    s.id = a.studentId AND 
    date(a.intime) = '2019-06-23')
WHERE
  s.inactivedate is null 
ORDER BY s.firstname, s.id

提示:

  • 为您的表格起别名。它会清理您的代码,并允许您多次连接同一张表
  • 缩进您的代码,而不仅仅是将它们放入一个巨大的块中;有助于查看查询的哪些部分去往-我缩进,以便查询中处于相同处理级别的所有内容都处于相同的缩进级别。诸如select,from,on和where的关键字在表单块标题中紧缩,然后缩进其中的所有内容
  • 请记住,始终将指向左连接中的右表(或右连接中的左表)的谓词放在ON而非位置

答案 1 :(得分:1)

我认为您只想要一个left join

Select a.id As AttendanceId, a.version, a.inTime, a.outTime, a.summary,
       a.id As StudentId, s.firstName, s.lastName 
From Student s join
     Attendance a
    on s.id = a.studentId and
       date(a.intime) = '2019-06-23' and
       a.inactiveDate is null
where s.inactivedate is null and        
order by s.firstname, s.id ;