如何从单独的子类表中进行选择?

时间:2013-05-07 02:24:02

标签: mysql sql relational-database

我有一个非常简单的数据库。这个想法是学生和教师都继承自“人”,这是由id和名字组成的。

create table Student (
    id int,
    name text,
    year int
);

create table Teacher (
    id int,
    name text,
    department varchar(15)
);

insert into Student (id, name, year) values
    (1, 'herper', 2007),
    (2, 'derpins', 2010);

insert into Teacher (id, name, department) values
    (3, 'skerp', 'csc');

我正在尝试创建一个将返回此选项的select语句:

id  name       year   department
1   'herper'   2007   NULL
2   'derpins'  2010   NULL
3   'skerp'    NULL   'csc'

这是我最接近的:

select *
from Student
union
select * from Teacher;

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

SELECT id, name, year, NULL department
  FROM Student
 UNION
SELECT id, name, NULL, department 
  FROM Teacher;

输出:

| ID |    NAME |   YEAR | DEPARTMENT |
--------------------------------------
|  1 |  herper |   2007 |     (null) |
|  2 | derpins |   2010 |     (null) |
|  3 |   skerp | (null) |        csc |

<强> SQLFiddle