php mysql连接查询别名

时间:2018-05-05 10:07:43

标签: php mysql

两张桌子。我想从设置表中选择2个名称。我想连接表对于这个简单的要求是太过分了,请告诉我。

错误号码:1066

不唯一的表/别名:'settings'

SELECT `parameter`.*, `settings`.`name` as `unitname`, `settings`.`name` as `sourcename` 
FROM `parameter` 
INNER JOIN `settings` ON `parameter`.`unit_id` = `settings`.`id` 
INNER JOIN `settings` ON `parameter`.`source_id` = `settings`.`id` 
WHERE `parameter`.`isdeleted` =0 
ORDER BY `parameter`.`id` DESC

1 个答案:

答案 0 :(得分:1)

你要加入同一个表两次,所以当你引用那个表时,查询引擎无法知道你指的是哪个连接表。别名表(在查询中为它们提供临时名称)以使它们可以单独识别:

SELECT
  `parameter`.*,
  `unit_settings`.`name` as `unitname`,
  `source_settings`.`name` as `sourcename`
FROM
  `parameter`
  INNER JOIN `settings` AS `unit_settings` ON `parameter`.`unit_id` = `unit_settings`.`id`
  INNER JOIN `settings` AS `source_settings` ON `parameter`.`source_id` = `source_settings`.`id`
WHERE
  `parameter`.`isdeleted` = 0
ORDER BY
  `parameter`.`id` DESC