为什么这个含糊不清?

时间:2014-02-18 12:36:32

标签: php sql

当我查询时:

$result = pg_query($dbconn, 
"SELECT w_bildurl, 
w_homepage_package_id AS whpi                         

FROM adempiere.w_homepage_package                           
LEFT JOIN adempiere.w_homepage_image ON adempiere.w_homepage_package.w_homepage_package_id = adempiere.w_homepage_image.w_homepage_package_id
LEFT JOIN adempiere.w_bilder ON adempiere.w_homepage_image.w_bilder_id = adempiere.w_bilder.w_bilder_id
WHERE sequence > 0
ORDER BY sequence ASC");

我得到了

 Query failed: ERROR: column reference 
"w_homepage_package_id" is ambiguous LINE 1:
 SELECT w_bildurl, w_homepage_package_id AS whpi

我认为在w_homepage_package_id中添加别名可以防止歧义。我是否必须将别名添加到LEFT JOIN或如何从查询中获取w_homepage_package_id?

3 个答案:

答案 0 :(得分:4)

您需要预先添加表别名,因为同一列位于多个表中,因此请按以下方式进行更改

SELECT tablealis.w_bildurl, 
tablealias.w_homepage_package_id AS whpi     

只需使用这些列所属的表的实际表别名更改tablealias

答案 1 :(得分:3)

因为您没有指定此列所属的表 以下代码可以使用:

  SELECT w_bildurl, 
         adempiere.w_homepage_package.w_homepage_package_id AS whpi                         
    FROM adempiere.w_homepage_package                           
         LEFT JOIN adempiere.w_homepage_image 
                   ON adempiere.w_homepage_package.w_homepage_package_id = adempiere.w_homepage_image.w_homepage_package_id
         LEFT JOIN adempiere.w_bilder 
                   ON adempiere.w_homepage_image.w_bilder_id = adempiere.w_bilder.w_bilder_id
   WHERE sequence > 0
ORDER BY sequence ASC

答案 2 :(得分:1)

你必须使用别名才能更好地使用,我已经实现了你的代码

<?php 

$result = pg_query($dbconn, 
"SELECT a.*,b.*,c.*                         

FROM adempiere.w_homepage_package as a                           
LEFT JOIN adempiere.w_homepage_image as b ON a.w_homepage_package_id = b.w_homepage_package_id
LEFT JOIN adempiere.w_bilder as c ON b.w_bilder_id = c.w_bilder_id
WHERE sequence > 0
ORDER BY sequence ASC");