-2

I have two tables:

attendance

  • attendance_id_pk
  • student_id
  • is_excused

checking

  • checking_id_pk
  • student_id
  • parent_consent

I want to join all data in the attendance table to checking table IF:

is_excused = true and parent_consent = false using student_id. It is possible that attendance table has no data in it. How to do this in postgresql?

4

3 回答 3

1

我猜您正在寻找的是一个结果集,checking即使表中没有匹配的记录,也会显示表中的记录attendance。如果是这种情况,那么您必须使用 OUTER 联接:

SELECT * FROM attendance RIGHT OUTER JOIN checking 
               ON (attendance.student_id = checking.student_id)
WHERE is_excused AND NOT parent_consent
于 2013-10-24T11:18:10.680 回答
0
 SELECT * FROM checking c
LEFT JOIN attendance a ON c.student_id = a.student_id AND a.is_excused = "true"
WHERE c.parent_consent = "false" 
于 2013-10-24T11:18:55.780 回答
0

尝试这个:

SELECT * FROM checking c
LEFT JOIN attendance a ON c.student_id = a.student_id AND a.is_excused = "true"
WHERE c.parent_consent = "false";

这将为您提供 parent_consent 为 false 的所有检查信息,以及每当您有 is_excused = true 的出勤信息时。

如果您不想在没有出席信息时检查信息,您可以执行以下操作:

SELECT * FROM checking c
INNER JOIN attendance a ON c.student_id = a.student_id 
WHERE c.parent_consent = "false"
AND a.is_excused = "true";

编辑:

如果您不想加入但要从两个表中获取所有信息,您可以执行以下操作:

SELECT checking_id_pk,student_id,parent_consent FROM checking c
WHERE c.parent_consent = "false"
UNION
SELECT attendance_id_pk,student_id,is_excused FROM attendance a
WHERE a.is_excused = "true";

在文档中查看有关 UNION 的更多信息:

UNION 有效地将 query2 的结果附加到 query1 的结果(尽管不能保证这是实际返回行的顺序)。此外,它以与 DISTINCT 相同的方式从其结果中消除重复行,除非使用 UNION ALL。

于 2013-10-24T11:05:54.523 回答