如何获取mysql查询中的最新商品价格?

时间:2017-09-30 10:22:27

标签: php mysql

我设法获得该商品的最低价,最高价和平均价,但无法获得最新价格。下面是我通过加入item和item_price表使用的select查询。我该如何解决这个问题?

$sql = 'SELECT *, MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price, 
        AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
        (SELECT ip_price FROM cnf_item_price WHERE ip_price_date = "latest_date") AS latest_price
        FROM cnf_item
        INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
        WHERE 1 AND cnf_item_price.ip_supp_id=?
        GROUP BY cnf_item.it_id
        ORDER BY cnf_item.it_name ASC';
$stmt = $DB->prepare($sql);
$stmt->bindValue(1,$supplier_id);
$stmt->execute();

3 个答案:

答案 0 :(得分:0)

您可以尝试以下查询:

$sql = 'SELECT *, MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price, 
        AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
        (SELECT ip_price FROM cnf_item_price order by ip_price_date desc limit 1) AS latest_price
        FROM cnf_item
        INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
        WHERE 1 AND cnf_item_price.ip_supp_id=?
        GROUP BY cnf_item.it_id
        ORDER BY cnf_item.it_name ASC';
$stmt = $DB->prepare($sql);
$stmt->bindValue(1,$supplier_id);
$stmt->execute();

答案 1 :(得分:0)

谢谢#ahmet kamaran。它在这里为我的案子工作。我也用其他人建议的那些列替换*。因此,经过上述建议的一些测试后,这里是我的代码,可以检索我需要的那些数据。

$sql = 'SELECT it_id, it_code, it_name, it_desc, 
        ip_id, ip_item_id, ip_supp_id, ip_price, ip_price_date, ip_ref_no, ip_remarks, 
        MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price,
        AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
        (SELECT ip_price FROM cnf_item_price ORDER BY ip_price_date DESC LIMIT 1) AS latest_price
        FROM cnf_item
        INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
        WHERE 1 AND cnf_item_price.ip_supp_id=?
        GROUP BY cnf_item.it_id
        ORDER BY cnf_item.it_name ASC';

$stmt = $DB->prepare($sql);
$stmt->bindValue(1,$supplier_id);
$stmt->execute();

http://sqlfiddle.com/#!9/ca6234/2

感谢。

答案 2 :(得分:0)

SELECT it_id, it_code, it_name, it_desc, 
            ip_id, ip_item_id, ip_supp_id, ip_price, ip_price_date, ip_ref_no, ip_remarks, 
            MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price,
            AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
            (SELECT ip_price FROM cnf_item_price WHERE cnf_item_price.ip_item_id = cnf_item.it_id
            ORDER BY ip_price_date DESC LIMIT 1) AS latest_price
            FROM cnf_item
            INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
            WHERE 1 
            GROUP BY cnf_item.it_id
            ORDER BY cnf_item.it_name ASC;