2015-10-13 173 views
-2

我有4種模式Mysql的加入和聯盟

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

而且需要找到由某個製造商製造的所有產品的型號和價格。如果可以用

(select model, price 
from Laptop) 
union 
(select model, price 
from PC) 
union 
(select model, price 
from Printer) 

得到的所有不同的產品只是價格和模型,但無法弄清楚如何將它與我的產品架構相結合,只得到了一定的製造商。

回答

1

使用子查詢可能會更有效率比多次join:

select model, price 
from (
    select model, price 
    from Laptop 
    union 
    select model, price 
    from PC 
    union 
    select model, price 
    from Printer 
) t join product p on t.model = p.model 
where p.maker = 'B' 
+0

謝謝,definitly看起來比我更好的版本。 – daemor

+0

@daemor - 沒問題,只要確保你別名的列 - '選擇t.model,t.price' ... – sgeddes

0

想通了

select Product.model, Laptop.price 
from Product, Laptop 
where Product.maker = 'B' and Product.model = Laptop.model 
union 
select Product.model, Printer.price 
from Product, Printer 
where Product.maker = 'B' and Product.model = Printer.model 
union 
select Product.model, PC.price 
from Product, PC 
where Product.maker = 'B' and Product.model = PC.model;