2014-09-20 59 views
0

*編輯:我正在使用sqlite3從多個表中查找最大值的問題

我有一個包含3個表的數據庫; pc,筆記本電腦和打印機。其中包括專欄模型和價格。我試圖從任何表格中選擇最高價格的模型。我的嘗試導致我:

select model 
from 
    (select model, max(price) 
    from 
     (select model, price 
     from laptop 
     union all 
     select model, price 
     from printer 
     union all 
     select model, price 
     from pc)); 

它給了我所有表中的最後一個模型。但如果我這樣做:

select model, p 
from 
    (select model, max(price) as p 
    from 
     (select model, price 
     from laptop 
     union all 
     select model, price 
     from printer 
     union all 
     select model, price 
     from pc)); 

它給了我正確的結果,但我堅持與價格以及。我不明白這是怎麼可能的。

+0

您正在使用什麼數據庫? (mysql,oracle,sql server等) – 2014-09-20 19:54:37

+0

使用'ORDER BY price DESC LIMIT 1'或'TOP 1 ... ORDER BY price DESC'或任何等價的關係型數據庫管理系統。 – Barmar 2014-09-20 19:55:38

+0

@BrianDeMilia我正在使用sqlite。 – 2014-09-20 19:56:47

回答

0

這應該做你想要什麼,並會帶回的關係,以及:

select x.model 
    from (select model, price 
      from laptop 
     union all 
     select model, price 
      from printer 
     union all 
     select model, price 
      from pc) x 
    join (select max(max_price) as max_price 
      from (select max(price) as max_price 
        from laptop 
       union all 
       select max(price) 
        from printer 
       union all 
       select max(price) 
        from pc)) y 
    on x.price = y.max_price