2016-07-06 95 views
0

我正在使用以下查詢來獲取與LIKE匹配的最低價格的行。SQL:加入LIKE和min()

Suppliers 
id | name   
---------------------------------------- 
1 | sup1  
2 | sup2 

Prices 
id | article_number | price | supplier_id 
------------------------------------------------ 
1 | 12345678  | 312 | 1 
2 | 12345678  | 219 | 2 
3 | 87654321  | 312 | 1 


select prices.* from prices 
inner join 
( 
    select min(price) as price, 
    article_number as article_number from prices group by article_number 
) 
min_prices on prices.price = min_prices.price 
and prices.article_number = min_prices.article_number 

WHERE prices.article_number LIKE '".$q."%' 

雖然現在還希望獲取來自供應商表的suppliers.name:

select prices.*, suppliers.name from prices, suppliers 
inner join 
( 
    select min(price) as price, 
    prices.article_number as article_number from prices group by prices.article_number 
) 
min_prices on price = min_prices.price 
and article_number = min_prices.article_number 

WHERE 
     prices.article_number LIKE '".$q."%' AND 
     prices.supplier_id = suppliers.id" 

這將返回行的18倍量的它應該是...?

此外,該表由10多百萬行組成,因此效率非常重要。

回答

1

對於性能,請在article_number上添加索引,並在子查詢中使用prices.article_number LIKE '".$q."%'。你最好使用JOIN而不是,(這是舊的方式)來組合兩個表。像這樣:

select prices.*, suppliers.name 
from prices 
inner join ( 
    select min(price) as price, prices.article_number as article_number 
    from prices 
    where prices.article_number like '".$q."%' 
    group by prices.article_number 
) min_prices 
on price = min_prices.price 
and article_number = min_prices.article_number 
inner join suppliers 
on prices.supplier_id = suppliers.id 
where prices.article_number like '".$q."%' 
+0

對於每個相關表格,從'show create table tablexyz'輸出。嘗試獲得一些合成索引,誰知道,即使是覆蓋索引。當然,從'explain'輸出。根據'article_number'的寬度,'(price,article_number)'上的組合可能會很甜 – Drew