【问题标题】:Why would a table be aliased twice in the same query?为什么一个表在同一个查询中会有两次别名?
【发布时间】:2018-12-16 01:59:51
【问题描述】:

这里是来自https://stackoverflow.com/a/2213199/3284469的查询,它得到一个表的索引信息。

为什么我们有两个别名pg_class by pg_class tpg_class i

i.oid = ix.indexrelid可以替换成t.oid = ix.indexrelid吗?

谢谢。

select
    t.relname as table_name,
    i.relname as index_name,
    a.attname as column_name
from
    pg_class t,
    pg_class i,
    pg_index ix,
    pg_attribute a
where
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and a.attrelid = t.oid
    and a.attnum = ANY(ix.indkey)
    and t.relkind = 'r'
    and t.relname like 'test%'
order by
    t.relname,
    i.relname;

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    通常在查询中为一个表命名两次,您需要从同一个表中引用两条不同的记录。

    常见的情况是表有一个自指针,例如每个员工指向一个经理的员工 - 另一个员工。即:

    EmpID   Name         ManagerID
    1       John Boss    NULL
    2       Mary Manager 1
    3       Brian        2
    4       Simon        2
    5       Susan        2
    

    上表中,John 为老板,Mary 向 John 汇报,其他三名员工向 Mary 汇报。

    如果您想获得每个员工及其老板的列表,您需要为该表命名两次:

    SELECT worker.Name, boss.ManagerName
    FROM 
        Employees AS worker
        LEFT JOIN Employees as boss ON worker.ManagerID = boss.EmpID
    

    您还可以使用它来汇总每一层监督下的员工工资成本等。

    因此,在您的问题中,不,您不能将一个替换为另一个,因为您实际上是从表中引用了一组不同的记录。

    您需要将 SQL 视为数据集,而不是表。这是学习高质量 SQL 的重要一步。一个集合可以由一个表、一个表的子集或由表组成的另一个查询、其他查询、常量或组合来表示。

    在这种情况下,基础表是多态的 - 它存储多种不同类型的数据。因此,子集用于引用表中的不同信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2016-10-11
      • 2022-01-18
      相关资源
      最近更新 更多