我有一个表结构
id, trackid, table_name, operation, oldvalue, newvalue, field, changedonetime
现在,如果我有 3 行相同的“trackid”相同的“字段”,那么我如何选择三行中的最新行?
即例如:
id = 100 trackid = 152 table_name = jos_menu operation = UPDATE oldvalue = IPL newvalue = IPLcccc field = name live = 0 changedonetime = 2010-04-30 17:54:39
和
id = 101 trackid = 152 table_name = jos_menu operation = UPDATE oldvalue = IPLcccc newvalue = IPL2222 field = name live = 0 changedonetime = 2010-04-30 18:54:39
正如您在上面看到的,第二个条目是最新的变化,现在我应该使用什么查询来从许多这样的行中获取唯一的一个和最新的行......
$distupdqry = "select DISTINCT trackid,table_name from jos_audittrail where live = 0 AND operation = 'UPDATE'";
$disupdsel = mysql_query($distupdqry);
$t_ids = array();
$t_table = array();
while($row3 = mysql_fetch_array($disupdsel))
{
$t_ids[] = $row3['trackid'];
$t_table[] = $row3['table_name'];
//$t_table[] = $row3['table_name'];
}
//echo "<pre>";print_r($t_table);echo "<pre>";
//exit;
for($n=0;$n<count($t_ids);$n++)
{
$qupd = "SELECT * FROM jos_audittrail WHERE operation = 'UPDATE' AND trackid=$t_ids[$n] order by changedone DESC ";
$seletupdaudit = mysql_query($qupd);
$row4 = array();
$audit3 = array();
while($row4 = mysql_fetch_array($seletupdaudit))
{
$audit3[] = $row4;
}
$updatefield = '';
for($j=0;$j<count($audit3);$j++)
{
if($j == 0)
{
if($audit3[$j]['operation'] == "UPDATE")
{
//$insqry .= $audit2[$i]['operation']." ";
//echo "<br>";
$updatefield .= "UPDATE `".$audit3[$j]['table_name']."` SET ";
}
}
if($audit3[$j]['operation'] == "UPDATE")
{
$updatefield .= $audit3[$j]['field']." = '".$audit3[$j]['newvalue']."', ";
}
}
/*echo "<pre>";
print_r($audit3);
exit;*/
$primarykey = "SHOW INDEXES FROM `".$t_table[$n]."` WHERE Key_name = 'PRIMARY'";
$prime = mysql_query($primarykey);
$pkey = mysql_fetch_array($prime);
$updatefield .= "]";
echo $updatefield = str_replace(", ]"," WHERE ".$pkey['Column_name']." = '".$t_ids[$n]."'",$updatefield);
}
在上面的代码中,我正在获取已完成更新操作的不同 ID,然后相应地触发查询以在所选不同 id 的不同字段上完成所有更改...这里我通过以下方式创建更新查询从最初描述的表中获取记录,此处称为 audittrail 表...因此我需要在该字段中进行最后一次更改,以便在我使用的选择查询中只能选择最新更改...
请仔细阅读代码..看看我最终如何进行所需的更改..