SQL not including duplicate values on a combination of 2 columns

∥☆過路亽.° 提交于 2020-01-06 02:55:08

问题


I am working on exercise 16 from sql-ex.ru. The problem asks the following:

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.

The database schema is :

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)

I wrote the following query:

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

But this displays duplicates of i,j as j,i. Here is my output:

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

As you can see, the values of i,j are flipped and counted as distinct values. Is there an easy way to get rid of duplicates like this? I am kind of lost on that part.


回答1:


I think the "model with higher number, model with lower number" in the problem statement is a clue that you need to have a A.model > B.model condition somewhere. Join's ON condition sounds like a fine candidate:

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

The <> is symmetrical; the > is not. Switching to > ensures that if {i, j} is in, then {j, i} will be out for sure.



来源:https://stackoverflow.com/questions/15888960/sql-not-including-duplicate-values-on-a-combination-of-2-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!