在添加到表之前检查10个新行的集合是否唯一,使用boolean记录

时间:2013-01-13 15:07:57

标签: php mysql

所以每天,我都会收集前十名,创建一个临时表 temp 。有一个大表时间轴,汇总了这些列表,其中包含以下列:

date, num, id, changed 

我想检查10本书的 temp 中的此设置是否唯一,或者它的源是否尚未更新且值是重复的。我希望在添加到时间轴之前,在 temp 中以布尔值已更改捕获此内容。

我确信有更好的方法可以做到这一点,但在PHP中,我创建了前一天的数组,并添加了最后一个数组,并与当前设置进行比较,将结果存储在单独的数组$ change_array中。我不知道如何将其添加回 temp ,即将此数组0和1转换为列,或者在一个命令中将值添加到各自的行中。仅供参考,这些命令如下所示:

$last_ten = "SELECT num, asin FROM timeline ORDER BY date DESC, num ASC LIMIT 0,10";
$cur_ten = "SELECT num, asin FROM temp ORDER BY num ASC";
...
for ($ind = 1; $ind <= 10; $ind++) {
    $change_array[$ind] = ($currents[$ind] == $prevs[$ind]) ? 0 : 1;
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

决定简化,使用array_intersect作为推荐,如果整个集合甚至是一行,那么该日期的所有行都被标记为不同:

$last_ten = "SELECT num, asin FROM timeline t ORDER BY t.date DESC, t.num ASC LIMIT 0,10";
$cur_ten = "SELECT num, asin FROM $table ORDER BY num ASC";

$prevs = array(1 => "", 2 => "", 3 => "", 4 => "", 5 => "", 6 => "", 7 => "", 8 => "", 9 => "",  10 => "");
    while($r = mysql_fetch_array($last_ten_res))
    {
        $num = $r['num'];
        $prevs[$num] = $r['asin'];
    }

$currents = array(1 => "", 2 => "", 3 => "", 4 => "", 5 => "", 6 => "", 7 => "", 8 => "", 9 => "",  10 => "");
    while($r = mysql_fetch_array($cur_ten_res))
    {
        $num = $r['num'];
        $currents[$num] = $r['asin'];
    }

$different = count(array_intersect($prevs, $currents)) == 10 ? 0 : 1;
$add_change = "ALTER TABLE $table ADD changed INT(1) DEFAULT $different;";