1

为什么此查询返回重复 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

错误:

数据库错误错误:SQLSTATE [42S21]:列已存在:1060 列名“id”重复 SQL 查询:SELECT DISTINCT * FROM products as prd LEFT OUTER JOIN (SELECT DISTINCT * FROM product_aliases) A​​S product_aliases ON product_aliases.product_id = prd.id AND product_aliases.alias = 'Pringles The Original' 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 = 1

4

1 回答 1

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

如果您不想一一列出

于 2013-01-27T21:37:55.963 回答