2010-10-25 53 views
0
TABLE PRODUCTS_CATEGORIES 

product_id category_id link_type position 
2    22    M   0 
3    22    M   0 
4    22    M   0 
5    22    M   0 
6    1    M   0 
7    1    M   0 
8    1    M   0 
9    1    M   0 
10   1    M   0 
11   1    M   0 


TABLE PRODUCT_PRICES 

product_id price lower_limit usergroup_id 
2   39.99 1   0 
3   69.99 1   0 
4   99.99 1   0 
5   124.99 1   0 
6   169.99 1   0 
7   199.99 1   0 
8   249.99 1   0 
9   24.99 1   0 
10   29.99 1   0 
11   34.99 1   0 

我希望能夠抓住從類別最低的產品價格 - 目前我所做的功能是:多個MySQL查詢和fatching MIN價格

function fn_get_category_min_price($category_id) 
{ 
    if (!empty($category_id)) 
    { 
     $product_min_price = db_get_field("SELECT product_id FROM ?:products_categories WHERE category_id = ?i", $category_id); 
     $category_min_price = db_get_field("SELECT MIN(price) FROM ?:product_prices WHERE product_id = ?i", $product_min_price); 
     if (!empty($category_min_price)) 
     { 
      return $category_min_price; 
     } 
     else 
     { 
      return ""; 
     } 
    } 
    return false; 
} 

但它不是100%的工作,雖然它抓住了正確的category_id的價格 - 它似乎並沒有抓住最低的時間....任何人有任何想法或更好的方式來編寫這些mysql查詢?

回答

1

據我所知,您的代碼從指定的類別中獲取第一個產品,然後返回它的價格。有時它是最小的,有時不是。

這可以用單個SQL查詢來完成:

select min(price) from product_prices p, product_categories c where p.product_id=c.product_id and c.category_id = $category_id 
+0

工作就像一個夢!謝謝 – james 2010-10-25 19:09:05

0

您可以用單個SQL查詢做到這一點通過連接兩個表(自然連接):

Select Min(`prize`) 
    from product_categories natural join product_prices 
    where category_id = ?i