Php 多个MySQL查询和从表中计算最低价格

Php 多个MySQL查询和从表中计算最低价格,php,mysql,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

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

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

但它并不是100%有效,尽管它从正确的分类id中获取了价格——它似乎并不是一直在获取最低的价格。。。。有人有什么想法或更好的方法来编写这些mysql查询吗???

据我所知,您的代码从指定的类别中获取第一个产品,然后返回它的价格。有时是最低限度,有时不是

这可以通过单个SQL查询完成:

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;
}

通过连接两个表(自然连接),您可以通过单个SQL查询实现这一点:

select min(price) from product_prices p, product_categories c where p.product_id=c.product_id and c.category_id = $category_id
Select Min(`prize`)
  from product_categories natural join product_prices
  where category_id = ?i