简体   繁体   English

“AS”在SQL中意味着什么?

[英]What does 'AS' mean in SQL?

Below is the synopsis of SELECT from the PostgreSQL documentation . 以下是PostgreSQL 文档SELECT的概要。 It seems to me that sometimes we write <expression> AS <name> and sometimes it's <name> AS <expression> . 在我看来,有时我们写<expression> AS <name> ,有时它是<name> AS <expression> In ordinary English, I tend to think <expression> AS <name> is much more common (eg "Address her as. Doctor Smith, please. , and I'm having trouble understanding how to think about <name> AS <expression> . 在普通的英语中,我倾向于认为<expression> AS <name>更为常见(例如“ 请将她称为。 史密斯博士,请。我很难理解如何考虑<name> AS <expression>

  1. How can we distinguish between where to use <name> AS <expression> and <expression> as <name> ? 我们如何区分使用<name> AS <expression><expression> as <name>
  2. What are minimal obvious examples of each? 什么是最简单的例子?
  3. Are there parallels of each kind in ordinary language, which would make it intuitively obvious when to use what? 在普通语言中是否存在各种类型的相似之处,这将使得何时使用什么直观明显?
 [ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] * | expression [ [ AS ] output_name ] [, ...] [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY expression [, ...] ] [ HAVING condition [, ...] ] [ WINDOW window_name AS ( window_definition ) [, ...] ] [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ] [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ] [ LIMIT { count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ] [ FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ] [...] ] where from_item can be one of: [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ] ( select ) [ AS ] alias [ ( column_alias [, ...] ) ] with_query_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ] function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ] function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] ) from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ] and with_query is: with_query_name [ ( column_name [, ...] ) ] AS ( select | values | insert | update | delete ) TABLE [ ONLY ] table_name [ * ] 

I like the question. 我喜欢这个问题。

Here is how I see it and how I explain it to people, hope it helps: 以下是我如何看待它以及如何向人们解释它,希望它有所帮助:

Let's start with <expression> as <name> . 让我们从<expression> as <name>开始, <expression> as <name> The simplest analogy from real life is an abbreviation. 现实生活中最简单的比喻是缩写。 It was created to make the code cleaner, easier to read and simply shorter. 它的创建是为了使代码更清晰,更易于阅读并且更简单。 Let's imagine a scenario: we have data on all students from the Massachusetts Institute of Technology as well as Massachusetts Department of Motor Vehicles in our database and we want to find students that have speeding tickets and how much they have paid. 让我们想象一个场景:我们在我们的数据库中有来自麻省理工学院马萨诸塞州汽车部门的所有学生的数据,我们希望找到有超速票和学费的学生。

SELECT
    government.SocialSecurityAdministration.FirstName,
    government.SocialSecurityAdministration.LastName,
    education.MasachusettsInstituteOfTechnology.Faculty
    government.DepartmentOfMotorVehiclesTickets.TicketTotal,
    government.SocialSecurityAdministration.SocialSecurityNumber
FROM
    education.MasachusettsInstituteOfTechnology
    INNER JOIN government.DepartmentOfMotorVehiclesTickets ON education.MasachusettsInstituteOfTechnology.SocialSecurityNumber = government.DepartmentOfMotorVehicles.SocialSecurityNumber
    INNER JOIN government.SocialSecurityAdministration ON government.DepartmentOfMotorVehicles.SocialSecurityNumber = government.SocialSecurityAdministration.SocialSecurityNumber

Looks ugly, doesn't it? 看起来很难看,不是吗? In real life, we've abbreviated the Massachusetts Institute of Technology to be MIT and the Department of Motor Vehicles to be DMV . 在现实生活中,我们简称麻省理工学院 MIT可以和机动车的部门是DMV。 I'm not aware of the official abbreviation for Social Security Administration (but we can come up with one) though we say SSN when we mean Social Security Number . 我不知道社会保障管理局的官方缩写(但我们可以提出一个)虽然我们说的是社会安全号码时的SSN Let's implement this idea: 让我们实现这个想法:

SELECT
        ssnAdm.FirstName,
        ssnAdm.LastName,
        ssnAdm.Faculty
        dmv.TicketTotal,
        ssnAdm.SocialSecurityNumber AS ssn
    FROM
        education.MasachusettsInstituteOfTechnology AS mit
        INNER JOIN government.DepartmentOfMotorVehiclesTickets AS dmv ON mit.SocialSecurityNumber = dmv.SocialSecurityNumber
        INNER JOIN government.SocialSecurityAdministration AS ssAdm ON dmv.SocialSecurityNumber = dmv.SocialSecurityNumber

Looks better now, doesn't it? 现在看起来更好,不是吗?

Now to the <name> as <expression> portion of it. 现在以<name> as <expression>部分。 This is done to simplify the code as well as some performance optimizations but let's focus on simplification for now. 这样做是为了简化代码以及一些性能优化,但现在我们将重点放在简化上。 Using the same example I've used above, you might want to get/ask the following: " For every MIT student that has received a ticket I need to know the last 4 digits of their SSN, their last name, the amount of money in their bank account and their last VISA transaction amount ". 使用我上面使用的相同示例,您可能想要/询问以下内容:“ 对于每个获得过机票的麻省理工学院学生,我需要知道他们的SSN的最后4位数字,他们的姓氏,金额在他们的银行账户和他们的最后VISA交易金额 “。 Yes, you work for CIA. 是的,你为CIA工作。

Let's write it: 我们来写吧:

SELECT
    RIGHT(4,ts.ssn) as LastFourDigitsSsn,
    ts.LastName,
    bad.TotalAmount,
    ISNULL(visa.TransactionAmt,'Student uses MasterCard') AS VisaTransaction
FROM
    (SELECT
        ssnAdm.FirstName,
        ssnAdm.LastName,
        ssnAdm.Faculty
        dmv.TicketTotal,
        ssnAdm.SocialSecurityNumber AS ssn
    FROM
        education.MasachusettsInstituteOfTechnology AS mit
        INNER JOIN government.DepartmentOfMotorVehiclesTickets AS dmv ON mit.SocialSecurityNumber = dmv.SocialSecurityNumber
        INNER JOIN government.SocialSecurityAdministration AS ssAdm ON dmv.SocialSecurityNumber = dmv.SocialSecurityNumber
    ) AS ts
    INNER JOIN business.BankAccountsData AS bad ON ts.ssn = bad.SocialSecurityNumber
    OUTER APPLY (SELECT TOP 1 TransactionAmt FROM business.VisaProcessingData vpd WHERE vpd.BankAccountID = bad.ID ORDER BY TransactionDateTime DESC) as visa

Well, looks ugly again. 好吧,看起来又丑陋了。 But what if we simplify it a bit and express certain things outside of the actual statement? 但是,如果我们稍微简化它并在实际陈述之外表达某些事情呢? That's when <name> as <expression> comes in. Let's do it: 那是<name> as <expression>进来的时候。让我们这样做:

WITH MitTicketedStudents AS (
    SELECT
        ssnAdm.LastName,
        ssnAdm.SocialSecurityNumber as ssn,
        RIGHT(4,ssnAdm.SocialSecurityNumber) as LastFourDigitsSsn
    FROM
        education.MasachusettsInstituteOfTechnology AS mit
        INNER JOIN government.DepartmentOfMotorVehiclesTickets AS dmv ON mit.SocialSecurityNumber = dmv.SocialSecurityNumber
        INNER JOIN government.SocialSecurityAdministration AS ssAdm ON dmv.SocialSecurityNumber = dmv.SocialSecurityNumber
),
LatestVisaTransactions AS (
    SELECT DISTINCT
        BankAccountID,
        FIRST_VALUE(TransactionAmt) OVER (PARTITION BY BankAccountId ORDER BY TransactionDateTime DESC) as TransactionAmt
    FROM
        business.VisaProcessingData
)

-- And let's use our expressions now

SELECT
    mts.LastFourDigitsSsn,
    mts.LastName,
    bad.TotalAmount,
    ISNULL(lvt.TransactionAmt,'Student uses MasterCard') AS VisaTransaction
FROM
    MitTicketedStudents mts
    INNER JOIN business.BankAccountsData AS bad ON mts.ssn = bad.SocialSecurityNumber
    LEFT OUTER JOIN LatestVisaTransactions lvt ON bad.ID = lvt.BankAccountID;

Looks better, doesn't it? 看起来更好,不是吗?

Conclusion: when you want to separate code you use <name> as <expression> , when you want to give something an alias to simplify code you use <expression> as <name> . 结论:当您想要分隔代码时,使用<name> as <expression> ,当您想要为别名提供别名以简化代码时,可以使用<expression> as <name>

What matters is where it appears. 重要的是它出现的地方。

mytable:
mycolumn myothercolumn
----------------------
       1             a
       2             b

SELECT myrow.mycolumn * 2 AS mylabel
FROM (SELECT * FROM mytable) AS myrow
WHERE myrow.mycolumn > 1

mylabel
-------
      4

In SELECT, we refer to the value of an expression AS some output column name ("column alias"). 在SELECT中,我们引用表达式AS的值作为一些输出列名(“列别名”)。 In FROM, we refer to (a typical row of) the value of a table expression AS some name ("table alias", "correlation name"). 在FROM中,我们引用(一个典型的行)表表达式AS值的某个名称(“表别名”,“相关名称”)。

(It turns out that because of details of the grammar typos are less problematic if we use AS in SELECT clauses but don't use AS in FROM clauses.) (事实证明,如果我们在SELECT子句中使用AS但在FROM子句中不使用AS,则因为语法错别字的细节问题较少。)

There are other uses of AS. AS还有其他用途。 The context also determines what they mean, and they also correspond to using using a name to refer to something. 上下文也决定了它们的含义,它们也对应于使用名称来引用某些内容。

In technical contexts it turns out not to be helpful to try to make sense of what something means based on the everyday meanings of technical terms, including making sense of what a thing is based on its name. 在技​​术背景下,根据技术术语的日常含义来尝试理解某些东西意味着什么并没有帮助,包括根据其名称来理解事物是什么。 The SQL language designers [sic] didn't choose to always have either <expression> AS <name> or <name> AS <expression> . SQL语言设计者[sic]没有选择始终具有<expression> AS <name><name> AS <expression> That is just how it is. 就是这样。 That is just how you write stuff to get your program to do stuff to stuff. 这就是你如何写东西让你的程序做东西。 (Accepted but more modern principles of computer language design do suggest more regular notations.) (接受但更现代的计算机语言设计原则确实建议更多的常规符号。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM