2

我必须从表“products”中输出一些产品,以及表“product_licenses”中的最低价格,这是我在此查询中需要从该表中获取的唯一列。

但是,当我尝试使用 sql 函数 MIN() 时,我的循环只运行一次代码并获得第一个结果然后停止,所以我在这里有点迷失。

这是使用 min() 的查询:

$mysql->query("
    SELECT pd.*, min(lc.price) AS price
    FROM `products` AS pd, product_licenses AS lc
    WHERE pd.`status` = '1' AND lc.product_id = pd.id
    ORDER BY pd.`id` ASC
    $limitQuery
");

我正在使用此功能来获取产品,但不幸的是,这获取了最高价格:

public function getAllProducts($start = 0, $limit = 0, $order = '`datetime` ASC') {
    global $mysql;


    $limitQuery = '';
    if ($limit != 0) {
        $limitQuery = " LIMIT $start,$limit ";
    }
    **// Not working if I use min() on lc.price**
    $mysql->query("
        SELECT pd.*, lc.price
        FROM `products` AS pd, product_licenses AS lc
        WHERE pd.`status` = '1' AND lc.product_id = pd.id
        ORDER BY pd.`id` ASC
        $limitQuery
    ");

    if ($mysql->num_rows() == 0) {
        return false;
    }

    $this->usersWhere = '';
    $return = array();
    while ($d = $mysql->fetch_array()) {
        $categories = explode(',', $d['category_id']);
        unset($d['category_id']);
        foreach ($categories as $c) {
            $c = trim($c);
            if ($c != '') {
                $d['category_id'][$c] = $c;
            }
        }

        $return[$d['id']] = $d;
    }

    $this->foundRows = $mysql->getFoundRows();

return $return;
}
4

3 回答 3

4

您的查询中没有group by子句,因此查询仅返回第一行。

SELECT pd.col1, pd.col2, pd.col3,  min(lc.price) AS price
FROM `products` AS pd, product_licenses AS lc
WHERE pd.`status` = '1' AND lc.product_id = pd.id
group by pd.col1, pd.col2, pd.col3
ORDER BY pd.`id` ASC
$limitQuery
于 2012-08-27T13:43:22.283 回答
4

你需要一个GROUP BY在那里,像这样:

SELECT pd.*, min(lc.price) AS price
FROM `products` AS pd, product_licenses AS lc
WHERE pd.`status` = '1' AND lc.product_id = pd.id
GROUP BY pd.`id`
ORDER BY pd.`id` ASC
$limitQuery

请注意,使用 MySQL,即使您从 products 表中选择其他列,您也只需要按 id 列进行分组。

于 2012-08-27T13:43:27.653 回答
4

添加GROUP BY您的查询。您当前的查询仅返回一个结果,因为您使用的是聚合函数(MIN)但没有对其进行分组。

SELECT  pd.col1, 
        pd.col2, min(lc.price) AS PRICE
FROM   `products` AS pd
             INNER JOIN product_licenses AS lc
                  ON lc.product_id = pd.id
WHERE    pd.`status` = '1' 
GROUP BY pd.col1, pd.col2, pd.col3
ORDER BY pd.`id` ASC
$limitQuery

PS:用记录发布数据库的结构。它会让社区清楚地理解你的问题:)

于 2012-08-27T13:44:03.427 回答