【问题标题】: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如何从一个表或另一个表中获取相同类型的行以及有关它来自哪个表的信息
【发布时间】:2016-06-19 13:01:38
【问题描述】:

假设我有桌子:

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 );

现在我想在惯用的方式。

我如何形成查询(如果已经部署了此类数据库)以及解决该问题的更好和更惯用的方法(如果到目前为止尚未部署)。

MariaDB 5.5,Go 访问的数据库,仅此而已。

提前致谢。

【问题讨论】:

  • 样本数据和预期结果会有所帮助。

标签: mysql sql go mariadb


【解决方案1】:

您说您需要知道数据来自哪个表。您可以为此使用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

【讨论】:

  • 谢谢!现在看起来很简单。只需确保我理解一个问题:只有当我有一个既是学生又是老师的人时才需要 ALL 关键字?
  • @ArchieT——不客气。要回答您的问题,不,union all 用于组合来自多个查询的结果——每个 sql 语句必须具有相同数量的列。加上union all 本身比union 快,因为union 删除了重复项。在您的情况下,这绝不应该发生。
【解决方案2】:

无需查看您的表格或任何关于您希望在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多