在SQL中使用别名的正确方法

时间:2018-03-21 11:17:29

标签: sql

我对SQL有疑问。下面我从Prestashop 1.6中的订单控制器查询。问题是。为什么我有ps_orders的两个别名?请查看以下查询:

SELECT SQL_NO_CACHE SQL_CALC_FOUND_ROWS
       a.`id_order`,
       `reference`,
       `total_paid_tax_incl`,
       `payment`,
       a.`date_add` AS `date_add`,
       a.id_currency,
       a.id_order AS id_pdf,
       CONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) AS `customer`,
       osl.`name` AS `osname`,
       os.`color`,
       IF(
            (SELECT COUNT(id_customer)
             FROM `ps_orders` so
             WHERE so.id_customer = a.id_customer) = 1, "Tak", "Nie") AS first_order,
       IF(
            (SELECT so.id_order
             FROM `ps_orders` so
             WHERE so.id_customer = a.id_customer
               AND so.id_order < a.id_order
             LIMIT 1) > 0, 0, 1) AS NEW,
       country_lang.name AS cname,
       IF(a.valid, 1, 0) badge_success
FROM `ps_orders` a
LEFT JOIN `ps_customer` c ON (c.`id_customer` = a.`id_customer`)
LEFT JOIN `ps_address` address ON address.id_address = a.id_address_delivery
LEFT JOIN `ps_country` country ON address.id_country = country.id_country
LEFT JOIN `ps_country_lang` country_lang ON (country.`id_country` = country_lang.`id_country`
                                             AND country_lang.`id_lang` = 6)
LEFT JOIN `ps_order_state` os ON (os.`id_order_state` = a.`current_state`)
LEFT JOIN `ps_order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state`
                                        AND osl.`id_lang` = 6)
WHERE 1
ORDER BY a.`id_order` DESC
LIMIT 0, 50

我在另一个a.id_orderso.id_order。也许我错了,但我的事情与ps_orders相同。第一个声明是ps_orders so,第二声明是ps_orders a?为什么有人在同一个表中使用两个别名?

2 个答案:

答案 0 :(得分:1)

一个别名用于主查询,另一个用于子查询。

主查询和每个子查询必须使用别名,因为它们都引用与主查询相同的表。

这是子查询与主查询中使用的同一个表中的记录相关的唯一方式 - 就像您进行自联接一样 - 在查询中多次使用相同的表(或视图) ,你必须使用不同的别名。

答案 1 :(得分:1)

一般查询如下:

SELECT
    A.SomeColumn
FROM
    YourTable A

如果您有子查询,那么

SELECT
    A.SomeColumn,
    (SELECT SomeOtherColumn FROM AnotherTable) ColumnAlias
FROM
    YourTable A

如果您的子查询包含相同的表,您可能希望使用不同的别名来区分它们!

SELECT
    A.SomeColumn,
    (SELECT B.SomeColumn FROM YourTable B) ColumnAlias
FROM
    YourTable A

子查询中引用的表中的列不能在外部引用:

SELECT
    A.SomeColumn,
    (SELECT B.SomeOtherColumn FROM YourTable B) ColumnAlias,
    B.SomeOtherColumn -- What table is B here? Outside scope!
FROM
    YourTable A

但是来自外部的列可以在里面引用!

SELECT
    A.SomeColumn,
    (SELECT B.SomeOtherColumn FROM YourTable B WHERE B.SomeOtherColumn = A.SomeColumn) ColumnAlias,
FROM
    YourTable A

PD:我在这些例子中假设子查询返回1行。