2011-05-19 32 views
3

我想解決一個SQL演習。尋找PC模型對

這裏的架構

PC

code  int 
model varchar(50) 
speed smallint 
ram  smallint 
hd  real 
cd  varchar(10) 
price money 

問題:

找到對具有 類似的速度和RAM PC機型。結果, 每個結果對只顯示 一次,即(i,j)但不顯示(j,i)。

我寫了一個查詢,但它顯示(i,j)和(j,i)。

我的查詢:

select t1.model,t2.model,t1.speed,t1.ram from pc t1 , pc t2 
where t1.speed = t2.speed and t1.ram = t2.ram and t1.model != t2.model 

輸出:

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 

需要的輸出:

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

那麼,如何避免(J,I)在我的輸出?

謝謝。

+0

我給予好評AIX和伊什塔爾,但我會去伊什塔爾;將'!='更改爲'>'。 – MatBailie 2011-05-19 14:42:31

回答

5

您的輸出和所需輸出之間的差異恰恰是具有t1.model < t2.model的行。要刪除這些,只需添加另一個AND t1.model >= t2.model。但是,因爲你已經要求t1.model != t2.model,完整的查詢是

select t1.model,t2.model,t1.speed,t1.ram 
from pc t1 , pc t2 
where t1.speed = t2.speed and t1.ram = t2.ram and t1.model > t2.model 
4

假設code是唯一的,您可以將配對限制爲t1.code < t2.code

2

SELECT DISTINCT als1.model,als2.model,als1.speed,als1.ram從PC ALS1,PC ALS2 WHERE(als1.speed = ALS2。速度)AND(als1.ram = als2.ram)AND(als1.model> als2.model)

這將解決您獲取(j,i)的問題。需要過濾器來避免雙重結果,因此使用最後一個過濾器(als1.model> als2.model),您可以選擇是否需要(i,j)或(j,i)。

1
 select pc1.model,pc2.model,pc1.speed,pc1.ram 
    from pc pc1,pc pc2 
    where pc1.speed=pc2.speed and pc1.ram= pc2.ram 
    group by pc1.model, pc2.model, pc1.speed, pc1.ram 
    having pc1.model> pc2.model 
+0

我真的嘗試過,它真的有用。 – grace 2014-08-09 12:29:06

2
SELECT DISTINCT t.model, l.model, t.speed, t.ram 
FROM PC as t JOIN PC as l 
ON t.speed = l.speed AND t.ram = l.ram 
AND t.model>l.model 

這應該讓當前和二級數據庫上正確的解決方案

1

下面的代碼工作好,因爲我們需要兩次返回模型列,並獲得速度和RAM數據,並確保我們限制該模型數據不重複,我們需要添加條件t1.model > t2.model

SELECT t1.model, 
     t2.model, 
     t1.speed, 
     t1.ram 
FROM pc t1, 
    pc t2 
WHERE t1.speed = t2.speed 
    AND t1.ram= t2.ram 
GROUP BY t1.model, 
     t2.model, 
     t1.speed, 
     t1.ram 
HAVING t1.model > t2.model