2012-12-13 64 views
1

我正在做的SQL查詢的練習,但得到的地方,我有3列具有相同的名稱,其中一些包含空,什麼是選項,所以我可以將它們合併成一個列調用價格,而不是3SQL查詢結合列

Short database description "Computer firm": 

The database scheme consists of four tables: 
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) 

表「產品」包括關於製造商,型號,類型(「PC」,「筆記本電腦」或「打印機」)的信息。假定產品表中的型號對於所有制造商和產品類型都是唯一的。每個通過表格「PC」中的代碼唯一指定的PC通過型號(外鍵參考產品表),速度(以MHz爲單位的處理器),RAM總量 - RAM(以Mb爲單位),硬盤驅動器容量 - 高清(以GB爲單位),CD ROM速度 - cd(例如'4x')和價格。表格「筆記本電腦」類似於除了CD ROM速度之外的其他個人電腦,它被屏幕尺寸 - 屏幕(以英寸)取代。對於表格「打印機」中的每臺打印機,會告知打印機是否爲彩色(彩色打印機的顏色屬性爲'y',否則爲'n'),打印機類型(激光,噴墨或矩陣)以及價格

練習:7 瞭解(任何類型)的所有產品的型號和價格由製造商生產B.

我的查詢:

SELECT distinct Product.model, PC.price, Laptop.price,Printer.price as price 
from Product 
left join PC 
on  Product.model=PC.model 
left JOIN Laptop 
ON Product.model=Laptop.model 
left join Printer 
on Product.model= Printer.model 
where Product.maker='B'; 

輸出:

您的查詢:

model price price price 
1121 850  NULL NULL 
1750 NULL 1200 NULL 

正確的查詢:

model price 
1121 850 
1750 1200 

回答

2

嘗試使用COALESCE

SELECT distinct Product.model, 
     COALESCE(PC.price, Laptop.price,Printer.price) as price 
from Product left join PC 
      on Product.model = PC.model 
    left JOIN Laptop 
      ON Product.model = Laptop.model 
    left join Printer 
      on Product.model = Printer.model 
where Product.maker='B' 

自定義,

COALESCE Returns the first nonnull expression among its arguments. 

更新1

SELECT a.model, a.price 
FROM PC a INNER JOIN Product b 
      ON a.model = b.model 
WHERE b.maker = 'makerB' 
UNION 
SELECT a.model, a.price 
FROM Laptop a INNER JOIN Product b 
      ON a.model = b.model 
WHERE b.maker = 'makerB' 
UNION 
SELECT a.model, a.price 
FROM Printer a INNER JOIN Product b 
      ON a.model = b.model 
WHERE b.maker = 'makerB' 
+0

但有沒有其他方式來解決這個問題? – keivn

+0

問題來自另一個網站的權利? 'http:// sql-ex.ru /',你的意思是有沒有其他方式? –

+0

是的,它來自那邊,我得到了相同的結果集,但它表示它不能在另一個測試中進行測試。和它顯示它使用聯合的例子,但我想要這樣做加入 – keivn

0

您可以使用UNION

SELECT Product.model, newTbl.price FROM Product 
    INNER JOIN 
(
SELECT model, price FROM PC 
    UNION 
SELECT model, price FROM Laptop 
    UNION 
SELECT model, price FROM Printer 
)newTbl ON Product.model = newTbl.model 

,或者如果你只需要只表產品是模型 1列,您可以將本產品表這樣

SELECT model, price FROM PC 
     UNION 
SELECT model, price FROM Laptop 
     UNION 
SELECT model, price FROM Printer 
-1
SELECT AVG(price) FROM (
    SELECT price, model 
    FROM pc 
    WHERE model IN (
     SELECT model 
     FROM product 
     WHERE maker='A' AND type='PC' 
    ) 
    UNION ALL 
    SELECT price, model 
    FROM laptop 
    WHERE model IN (
     SELECT model 
     FROM product 
     WHERE maker='A' AND type='Laptop' 
    ) 
) as prod 
+0

一點描述就會很好 – wonko79