2014-02-24 68 views
0

我怎麼能得到這個SQL語句更小,就像只在某處使用WHERE來獲得更快的結果?謝謝!SQL如何更快地從語句中獲得結果?

SELECT p.model, pc.price FROM Product AS p 
JOIN PC AS pc 
    ON pc.model = p.model 
WHERE p.maker='B' 

UNION 
SELECT p.model, lp.price FROM Product AS p 
JOIN Laptop AS lp 
    ON p.model = lp.model 
WHERE p.maker='B' 

UNION 
SELECT p.model, pr.price FROM Product AS p 
JOIN Printer AS pr 
    ON p.model = pr.model 
WHERE p.maker='B' 

編輯:我想它要快。

+2

非常容易閱讀,因爲它是。爲什麼改變它? –

+0

我教了也許有一個更好/更快的方式來獲得結果。 –

+1

除了標準化爲一個產品表,並有一個指定類型的標識符... –

回答

0

我可能會保持原樣,除非您打算增加更多內容。但作爲你的問題的文字回答:

select pr.model, 
     case 
     when pc.price is not null then 
      pc.price 
     when lp.price is not null then 
      lp.price 
     when pt.price is not null then 
      pt.price 
     else 
      null 
     end as price 
    from product pr 
    left join pc 
    on pr.model = pc.model 
    left join laptop lp 
    on pr.model = lp.model 
    left join printer pt 
    on pr.model = pt.model 
where pr.maker = 'B' 
+0

你可以用'coalesce(pc.price,lp.price,pt.price)'替換'case'。 –

+0

非常好!謝謝! –

-1

嘗試CTE。

Psuedo。不在終端前面。

With product as 
(
Select fields from PC union all 
Select fields from laptop union all 
Select fields from printers 
) 
Select fields from product where maker = b 
+0

是的,這是它!謝謝! –

+0

確保您的字段匹配。在前面添加分號。也許有人可以將它格式化爲我的代碼。對不起,我在我的手機上。 –

+0

即使沒有標記爲這樣我猜OP必須使用sql-server嗎? –

0

可能加快你的查詢的最佳方法是用union all來代替每個union,然後添加以下指標:

create index product_maker_model on produce(maker, model); 
create index pc_model_price on pc(model, price); 
create index laptop_model_price on laptop(model, price); 
create index printer_model_price on printer(model, price); 

查詢是:

SELECT p.model, pc.price 
FROM Product p JOIN 
    PC pc 
    ON pc.model = p.model 
WHERE p.maker = 'B' 
UNION ALL 
SELECT p.model, lp.price 
FROM Product p JOIN 
    Laptop lp 
    ON p.model = lp.model 
WHERE p.maker = 'B' 
UNION ALL 
SELECT p.model, pr.price 
FROM Product p JOIN 
    Printer pr 
    ON p.model = pr.model; 
WHERE p.maker = 'B'; 

同索引也將加速left outer join版本。哪個更快取決於各種因素,但左外部連接版本可能表現更好。

相關問題