该问题应该如何正确查询?

时间:2019-01-30 01:52:35

标签: sql postgresql

伙计们,我有一个问题,我要总结4个表格。

此数据库位于PostgreSQL上,模型关系是继承的

表1 :(人)

id: character
name: character    
last_name:character    
age: character

表2:学生(继承自Person)

id: character (imported from person)         
name: character (imported from person)        
last_name:character (imported from person)        
age: character (imported from person)    
college: character    
courses: character

TABLE3:老师(继承自Person)

id: character (imported from person)        
name: character (imported from person)        
last_name:character (imported from person)        
age: character (imported from person)    
license: integer    
date_empl: date
years_working: integer

我希望通过一个查询就可以获取代码所属的两个表之一的所有信息。

我做不到

SELECT *
FROM STUDENT
WHERE ID = {{whatever}}

因为是静态的,所以我想在另一个表中搜索(ID {{whatever}}

我尝试过

SELECT *
FROM STUDENT
WHERE ID = {{whatever}}

UNION ALL

SELECT *
FROM TEACHER
WHERE ID = {{whatever}}

但是它不起作用,因为UNION需要在2个表中具有相同的列数

如何仅通过一个查询就可以得到一个人的详细信息,无论是教授还是学生?还是我可以用什么方式?

1 个答案:

答案 0 :(得分:5)

使用UNION是一种解决方案。如果列不同,则可以在输出中生成几列,并在不可用的记录中用NULL填充它们。

SELECT id, name, last_name, age, college, courses, null, null FROM student
UNION ALL
SELECT id, name, last_name, age, null, null, license, date_empl FROM teacher