mysql - 如何从一个表或另一个表中获取相同类型的行以及有关它来自哪个表的信息

标签 mysql sql go mariadb

假设我有表格:

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/

相关文章:

mysql - 循环数组进行批量插入时错误的增量 Nodejs 和 MySQL

php - SQL SELECT 和 PHP 检索使用单表 VS 连接两个表的速度?

java - 将两个数据源连接到同一个数据库

sql - SQL Server 2005 有趣且具有挑战性的自连接问题

mysql - 截断分区后索引的命运

mysql - 如果语句为真,则乘以列

sql - 交易范围和准备好的报表

json - 从 json unmarshal 键入断言二维接口(interface)数组的更简单方法

Golang VSCode 配置最佳设置

sql - 随SQL Server驱动程序一起无法成功连接,登录失败