我有一个名为“定价”的表,其中包含许多字段,包括“发行商”和“版本”。经销商字段是经销商表中的 ID。每个发行商都有不同的版本。类似版本:20131109AV-V1,20131110AV-V2,20131112AV-V3 是distributor=1 的版本,20131111WC-V1,20131111WC-V2 是distributor=2 的版本等等。我需要从定价表中选择所有数据,其中版本等于每个经销商的最新版本。
例如:20131112AV-V3是distributor=1的最新版本 20131111WC-V2是distributor=2最新版本
可以一步查询吗?
或者我是否需要逐部分查询,例如首先选择经销商和版本,然后使用经销商和最新版本循环遍历表(代码如下:)?
$all_distributors=mysql_query("SELECT `distributor`,MAX(`version`) as `version` FROM `pricing` GROUP BY `distributor`",$con);
while($all_dist= mysql_fetch_array($all_distributors))
{
$latest_version=$all_dist['version'];
$distributor=$all_dist['distributor'];
echo $distributor."-".$latest_version."<br/>";
//Again select the query using this $distributor & $latest_version
}
有什么想法吗?
谢谢!
最佳答案
您可以使用单个查询来实现此目的:
SELECT p.*
FROM pricing p
JOIN
(
SELECT distributor, MAX(version) AS ver
FROM pricing
GROUP BY distributor
) mx ON mx.ver = p.version AND p.distributor = mx.distributor
关于php - 如何从版本字段是最新版本的数据库中进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918912/