【问题标题】:SQL not including duplicate values on a combination of 2 columnsSQL 不包括 2 列组合上的重复值
【发布时间】:2013-03-31 02:48:24
【问题描述】:

我正在练习 sql-ex.ru 的练习 16。问题问如下:

Find the pairs of PC models having identical speeds and RAM. 
As a result, each resulting pair is shown only once, i.e. (i, j) but not (j, i). 
Result set: model with higher number, model with lower number, speed, and RAM.

数据库架构是:

Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)

我写了以下查询:

SELECT A.model, B.model, A.speed, A.ram
FROM PC A
JOIN PC B ON (A.model<>B.model)
WHERE A.speed=B.speed
AND A.ram=B.ram

但这会将 i,j 的重复项显示为 j,i。这是我的输出:

model   model   speed   ram
1121    1233    750 128
1232    1233    500 64
1232    1260    500 32
1233    1121    750 128
1233    1232    500 64
1260    1232    500 32

如您所见,i,j 的值被翻转并计为不同的值。有没有一种简单的方法来摆脱这样的重复?我在这方面有点迷失了。

【问题讨论】:

    标签: sql join duplicate-removal


    【解决方案1】:

    我认为问题陈述中的“型号较高,型号较低”是您需要在某处具有A.model &gt; B.model 条件的线索。加入的ON 条件听起来不错:

    SELECT A.model, B.model, A.speed, A.ram
    FROM PC A
    JOIN PC B ON (A.model > B.model) -- <<<=== Here
    WHERE A.speed=B.speed
    AND A.ram=B.ram
    

    &lt;&gt; 是对称的; &gt; 不是。切换到&gt; 可以确保如果{i, j} 加入,那么{j, i} 肯定会退出。

    【讨论】:

    • 这是有道理的。没有考虑对称值。
    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多