连接三个表时使用别名

时间:2013-12-24 11:03:31

标签: sql sql-server

我想在SQL Server中使用以下SQL查询的别名:

      a.client_id, a.name, b.address_line_1, a.address_id, a.contact_id
    , b.address_id, c.email, c.mobile_number, c.telephone_number, c.contact_id
    , c.contact_first_name 
 from client a, address b, contact c 
where a.address_id = b.address_id and a.contact_id = c.contact_id 

我试过这个但是得到了一个例外

SELECT a.client_id AS a.ClientId
    ,a.NAME AS a.NAME
    ,a.address_id AS a AddressId
    ,a.contact_id AS a.ContactId
    ,b.address_line_1 AS b.AddressLine1
    ,b.address_id AS b.AddressId
    ,c.email AS c.Email
    ,c.mobile_number AS c.MobileNumber
    ,c.telephone_number AS c.TelephoneNumber
    ,c.contact_id AS c.ContactId
    ,c.contact_first_name AS c.ContactFirstName
FROM client a
    ,address b
    ,contact c
WHERE a.address_id AS a.AddressId = b.address_id AS b.AddressId
    AND a.contact_id AS a.ClientId = c.contact_id AS c.ClientId

3 个答案:

答案 0 :(得分:2)

您的陈述中有一些小错误。列别名不应以a.b.c.为前缀,并且不要在WHERE子句中添加别名。最好使用JOIN语句将表连接在一起,而不是将它们全部放入并使用WHERE子句来过滤它们。请参阅下面的示例,了解适用于您的内容:

SELECT
     a.client_id AS ClientId
    ,a.NAME AS NAME
    ,a.address_id AS AddressId
    ,a.contact_id AS ContactId
    ,b.address_line_1 AS AddressLine1
    ,c.email AS Email
    ,c.mobile_number AS MobileNumber
    ,c.telephone_number AS TelephoneNumber
    ,c.contact_first_name AS ContactFirstName
FROM
    client AS a
    INNER JOIN address AS b
        ON (a.address_id = b.address_id)
    INNER JOIN contact AS c
        ON (a.contact_id = c.contact_id)
;

答案 1 :(得分:1)

创建别名时,您无法使用.,因为它会给您语法错误。最好指定a.ClientId as aClientID, c.ClientId as cClientID

之类的别名

答案 2 :(得分:1)

您不能像在where州名一样使用别名

where a.somefield AS whatever = ...
                   ^ this is wrong

您不能像以前那样使用带别名的别名:

select a.client_id as a.client_id
                      ^ here

a.已经是您的表的别名,因此您只需根据需要为该字段命名即可。你应该这样做:

select a.client_id as FieldClientId