如何从一个 table 或另一个 table 中获取相同类型的行以及有关 table 来源的信息
How do I get a row of the same type from one table or another table along with the information about from which table it was
假设我有 tables:
create table people (
human_id bigint auto_increment primary key,
birthday datetime );
create table students (
id bigint auto_increment primary key,
human_id bigint unique key not null,
group_id bigint not null );
create table teachers (
id bigint auto_increment primary key,
human_id bigint unique key not null,
academic_degree varchar(20) );
create table library_access (
access_id bigint auto_increment primary key,
human_id bigint not null,
accessed_on datetime );
现在我想显示有关图书馆访问的信息,以及它是学生还是老师的信息(然后是与 table 对应的 ID)(假设我想要类似 SELECT access_id,id,true_if_student_false_if_teacher FROM library_access
), 以一种惯用的方式。
我如何形成查询(如果已经部署了这样的数据库)以及解决该问题的更好和更惯用的方法(如果到目前为止尚未部署)。
MariaDB 5.5,Go 访问的数据库,仅此而已。
提前致谢。
无需查看您的表格,也无需了解您想要在 select 语句中返回的内容:
SELECT *
FROM people a,
students b,
teachers c,
library_access d
WHERE a.human_id = b.human_id
AND a.human_id = c.human_id
AND a.human_id = d.human_id
你说你需要知道数据来自哪个table。您可以为此使用 union all
:
select la.access_id, s.id, 'Students' as source_table
from library_access la
join students s on la.human_id = s.human_id
union all
select la.access_id, t.id, 'Teachers' as source_table
from library_access la
join teachers t on la.human_id = t.human_id
假设我有 tables:
create table people (
human_id bigint auto_increment primary key,
birthday datetime );
create table students (
id bigint auto_increment primary key,
human_id bigint unique key not null,
group_id bigint not null );
create table teachers (
id bigint auto_increment primary key,
human_id bigint unique key not null,
academic_degree varchar(20) );
create table library_access (
access_id bigint auto_increment primary key,
human_id bigint not null,
accessed_on datetime );
现在我想显示有关图书馆访问的信息,以及它是学生还是老师的信息(然后是与 table 对应的 ID)(假设我想要类似 SELECT access_id,id,true_if_student_false_if_teacher FROM library_access
), 以一种惯用的方式。
我如何形成查询(如果已经部署了这样的数据库)以及解决该问题的更好和更惯用的方法(如果到目前为止尚未部署)。
MariaDB 5.5,Go 访问的数据库,仅此而已。
提前致谢。
无需查看您的表格,也无需了解您想要在 select 语句中返回的内容:
SELECT *
FROM people a,
students b,
teachers c,
library_access d
WHERE a.human_id = b.human_id
AND a.human_id = c.human_id
AND a.human_id = d.human_id
你说你需要知道数据来自哪个table。您可以为此使用 union all
:
select la.access_id, s.id, 'Students' as source_table
from library_access la
join students s on la.human_id = s.human_id
union all
select la.access_id, t.id, 'Teachers' as source_table
from library_access la
join teachers t on la.human_id = t.human_id