如何在 mysql 查询中获取最新的商品价格?
Posted
技术标签:
【中文标题】如何在 mysql 查询中获取最新的商品价格?【英文标题】:How can I get the latest item price in mysql query? 【发布时间】:2018-03-12 03:01:25 【问题描述】:我设法获得了该商品的最低、最高和平均价格,但无法获得最新价格。下面是我通过加入 item 和 item_price 表使用的选择查询。我该如何解决这个问题?
$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();
【问题讨论】:
1.不要使用邪恶的SELECT *
。修复它。然后回复我们。
要获得最后一次更新返回,您可以使用受 php 函数影响的行查看***.com/questions/7368225/…
哦,看看Why should I provide an MCVE for what seems to me to be a very simple SQL query
【参考方案1】:
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;
【讨论】:
【参考方案2】:谢谢#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
谢谢。
【讨论】:
【参考方案3】:您可以尝试以下查询:
$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();
【讨论】:
子选择应该是相关的。并且您不应该在带有 GROUP BY 的语句中使用SELECT *
。以上是关于如何在 mysql 查询中获取最新的商品价格?的主要内容,如果未能解决你的问题,请参考以下文章