为什么我必须使用DISTINCT才能工作?

时间:2010-06-28 15:13:25

标签: sql ms-access

这是我的问题:我有一个SQL查询,它对查找表进行4次调用,以从另一个表中的组合列表中返回它们的值。我终于得到了这个工作,并且出于某种原因,当我在没有DISTINCT的情况下运行查询时,我得到了大量的数据,所以我猜测我要么缺少某些东西,要么没有正确地执行此操作。如果这不仅可以工作,而且还会按照第一个颜色名称的字母顺序返回列表,那将是非常好的。 我把我的SQL放在这里我希望我已经解释得这么好了:

SELECT DISTINCT 
    colour1.ColourID AS colour1_ColourID, 
    colour1.ColourName AS colour1_ColourName, 
    colour1.ColourHex AS colour1_ColourHex, 
    colour1.ManufacturerColourID AS colour1_ManufacturerColourID, 
    colour2.ColourID AS colour2_ColourID, 
    colour2.ColourName AS colour2_ColourName, 
    colour2.ColourHex AS colour2_ColourHex, 
    colour2.QEColourID2 AS colour2_QEColourID2, 
    colour3.ColourID AS colour3_ColourID, 
    colour3.ColourName AS colour3_ColourName, 
    colour3.ColourHex AS colour3_ColourHex, 
    colour3.QEColourID3 AS colour3_QEColourID3, 
    colour4.ColourID AS colour4_ColourID, 
    colour4.ColourName AS colour4_ColourName, 
    colour4.ColourHex AS colour4_ColourHex, 
    colour4.QEColourID4 AS colour4_QEColourID4, 
    Combinations.ID, 
    Combinations.ManufacturerColourID AS Combinations_ManufacturerColourID, 
    Combinations.QEColourID2 AS Combinations_QEColourID2, 
    Combinations.QEColourID3 AS Combinations_QEColourID3, 
    Combinations.QEColourID4 AS Combinations_QEColourID4, 
    Combinations.ColourSupplierID, 
    ColourSuppliers.ColourSupplier 
FROM 
    ColourSuppliers INNER JOIN 
    (
        colour4 INNER JOIN 
        (
            colour3 INNER JOIN 
            (
                colour2 INNER JOIN 
                (
                    colour1 INNER JOIN Combinations ON 
                     colour1.ColourID=Combinations.ManufacturerColourID
                ) ON colour2.ColourID=Combinations.QEColourID2
            ) ON colour3.ColourID=Combinations.QEColourID3
        ) ON colour4.ColourID=Combinations.QEColourID4
    ) ON ColourSuppliers.ColourSupplierID=Combinations.ColourSupplierID 
WHERE Combinations.ColourSupplierID = ?

由于 斯蒂芬

2 个答案:

答案 0 :(得分:3)

看起来你可能在组合表中为每组四种颜色组合获得了多条记录 - 发布表格的结构可能有助于我们解决这个问题。

order by colour1.ColourName子句添加到查询末尾应按第一个颜色名称的字母顺序排序。

答案 1 :(得分:0)

我的猜测(这是猜测,因为你的SQL查询非常宽!)是你得到的笛卡尔积。