从表中多个MySQL查询和加载MIN价格

时间:2010-10-25 18:51:20

标签: php mysql

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

我希望能够从该类别中获得最低的产品价格 - 我目前的功能是:

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查询??

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以通过连接两个表(自然连接)来执行单个SQL查询:

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