假设我有表格:
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 );
现在我想显示有关图书馆访问的信息,以及它是学生还是老师的信息(然后是与表对应的 id)(假设我想要类似 SELECT access_id,id 的信息,true_if_student_false_if_teacher FROM library_access
), 以一种惯用的方式。
我如何形成查询(如果已经部署了这样的数据库)以及解决该问题的更好和更惯用的方法(如果到目前为止尚未部署)。
MariaDB 5.5,仅通过 Go 访问数据库。
提前致谢。
最佳答案
你说你需要知道数据来自哪个表。您可以为此使用 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
关于mysql - 如何从一个表或另一个表中获取相同类型的行以及有关它来自哪个表的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35818998/