我的表结构为
id,trackid,table_name,operation, oldvalue,newvalue,field, changedonetime
现在,如果我有3行用于相同的“trackid”相同的“字段”,那么我该如何选择最新的三个?
即。例如:
id = 100 trackid = 152 table_name = jos_menu 操作 =更新旧值 = IPL newvalue = IPLcccc 字段 =名称直播 = 0 已更改时间 = 2010-04-30 17:54:39
和
id = 101 trackid = 152 table_name = jos_menu 操作 =更新旧值 = IPLcccc newvalue = IPL2222 字段 =名称实时 = 0 已更改时间 = 2010-04-30 18:54:39
正如你在上面看到的那样,secind条目是最新的变化, 现在我应该使用什么查询来获得许多这样的行中唯一的一行和最新行...
$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的不同字段上完成的所有更改... 这里我通过从最初描述的表中获取记录来创建Update查询,这里提到的表是audittrail表... 因此,我需要在字段中进行最后一次更改,以便在我使用的选择查询中只能选择最新的更改...
请仔细阅读代码..看看我怎样才能做出最后需要的改变..
答案 0 :(得分:2)
这是另一个关于每组最大类别的问题,它在Stack Overflow上每周出现几次。
以下是我在你的案例中解决它的方法:
SELECT j1.*
FROM jos_audittrail j1 LEFT OUTER JOIN jos_audittrail j2
ON (j1.trackid = j2.trackid AND j1.field = j2.field
AND j1.changedonetime < j2.changedonetime)
WHERE j2.id IS NULL;