Mysql - 如何在左连接中对整个表进行别名

时间:2011-08-22 16:00:24

标签: mysql sql join alias

我的情况是属性表包含地址ID(来自g_addresses表),而申请人表保存g_addresses中的地址ID。 我想一起加入这些,但选择表格中的所有字段。

我知道使用'as'为字段创建别名,但有没有办法为整个表生成别名?

SELECT *
FROM (`reference`)
LEFT JOIN `applicants` ON `applicants`.`id` = `reference`.`applicant_id`
LEFT JOIN `g_people` applicant_person ON `applicant_person`.`id` = `applicants`.`person_id`
LEFT JOIN `g_addresses` applicant_address ON `applicant_address`.`id` = `applicants`.`address_id`
LEFT JOIN `properties` ON `properties`.`id` = `reference`.`property_id`
LEFT JOIN `g_addresses` property_address ON `property_address`.`id` = `properties`.`address_id`
WHERE `reference`.`id` = 4 

这会产生一个只包含一个地址行而不是两者的结果, 返回的行是最后一个连接的行而不是之前的行,表示它在返回时被覆盖。

2 个答案:

答案 0 :(得分:14)

在您的情况下,我认为您不应该使用屏蔽引用,例如*`reference`.*,因为您最终可能会得到一个包含相同列名的行集(idaddress_id)。

如果要从连接表中提取所有列,则应该在SELECT子句中单独指定它们,并为每个列分配唯一的别名:

SELECT
  ref.`id` AS ref_id,
  ref.`…`  AS …,
  …
  app.`id` AS app_id,
  …
FROM `reference` AS ref
LEFT JOIN `applicants`  AS app ON app.`id` = ref.`applicant_id`
LEFT JOIN `g_people`    AS ape ON ape.`id` = app.`person_id`
LEFT JOIN `g_addresses` AS apa ON apa.`id` = app.`address_id`
LEFT JOIN `properties`  AS pro ON pro.`id` = ref.`property_id`
LEFT JOIN `g_addresses` AS pra ON pra.`id` = pro.`address_id`
WHERE ref.`id` = 4

答案 1 :(得分:1)

更具体地说明您选择的列

SELECT 
  applicant_address.*,
  property_address.*,
  applicants.*,
  applicant_person.*,
  properties.*
FROM (`reference`)
LEFT JOIN `applicants` ON `applicants`.`id` = `reference`.`applicant_id`
LEFT JOIN `g_people` applicant_person ON `applicant_person`.`id` = `applicants`.`person_id`
LEFT JOIN `g_addresses` applicant_address ON `applicant_address`.`id` = `applicants`.`address_id`
LEFT JOIN `properties` ON `properties`.`id` = `reference`.`property_id`
LEFT JOIN `g_addresses` property_address ON `property_address`.`id` = `properties`.`address_id`
WHERE `reference`.`id` = 4