2015-10-13 129 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;