如何选择在给定表结构中完成的最新更改?

时间:2010-05-03 05:17:20

标签: mysql select

我有一个表结构 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);   
}

这里我通过从最初描述的表中获取记录来创建Update查询,这里提到的是audittrail表...请仔细阅读代码..看看我怎样才能最终得到所需的更改...

1 个答案:

答案 0 :(得分:1)

select * from TableName order by id DESC LIMIT 1

编辑。如果您想通过“changedonetime”USE订购,可以使用YE。

select * from TableName order by changedonetime DESC LIMIT 1