查询错误重复列id sql

时间:2013-01-27 21:30:47

标签: php mysql sql

为什么此查询返回错误的重复ID?我正在使用php

SELECT DISTINCT * FROM products  as prd
    LEFT OUTER JOIN  (SELECT DISTINCT * FROM product_aliases) AS product_aliases
    ON product_aliases.product_id = prd.id 
    AND product_aliases.alias = '$alias'

    LEFT OUTER JOIN  (SELECT DISTINCT * FROM product_images as prdim
        LEFT OUTER JOIN  product_image_votes as prdimvt 
            ON prdimvt.product_image_id = prdim.id) AS productimages 
    ON productimages.product_id = prd.id 
WHERE prd.id = $id

ERROR:

  

数据库错误错误:SQLSTATE [42S21]:列已存在:1060   重复的列名'id'SQL查询:SELECT DISTINCT * FROM products   as prd LEFT OUTER JOIN(SELECT DISTINCT * FROM product_aliases)AS   product_aliases ON product_aliases.product_id = prd.id AND   product_aliases.alias ='Pringles The Original'LEFT OUTER JOIN   (选择DISTINCT * FROM product_images作为prdim LEFT OUTER JOIN   product_image_votes as prdimvt ON prdimvt.product_image_id = prdim.id)   AS productimages ON productimages.product_id = prd.id WHERE prd.id = 1

1 个答案:

答案 0 :(得分:2)

您的查询中有3个表,其中至少有2个表具有相同的列id。在您的选择中使用*会选择这三个表中的所有列,多次选择id

您可以通过使用别名

指定列来解决此问题
SELECT DISTINCT prd.id, prd.Name FROM products  as prd
LEFT OUTER JOIN  (SELECT DISTINCT * FROM product_aliases) AS product_aliases
ON product_aliases.product_id = prd.id 
AND product_aliases.alias = '$alias'
... rest of your query here

您也可以

SELECT DISTINCT prd.* FROM products  as prd

如果您不想逐一列出