根据行数和条件删除记录

时间:2018-03-20 15:55:34

标签: php mysql pdo

我正在尝试创建一个快速修复脚本,以便删除一些记录并使数据恢复正常。

最初我有销售记录插入并使用数量值来创建相同数量的记录。所以如果我插入一个数量值为12的记录,那么我会插入该记录的12个。这为每个SKU提供了自己的记录,以便个人可以更新日期。

然而,这已经改变了,我现在需要根据商店位置而不是数量来做,所以在某些情况下我的记录太多了。

如果我使用当前查询运行脚本(对于经销商编号145),它会按预期选择他们今年订购的所有skus。我现在需要运行一个delete语句,它接受每个sku的行数并将其与连接的店面值进行比较。

所以,如果storefronts = 10并且该sku / dealer组合有25条记录,那么我需要删除最旧的15条。这里的逻辑是for each sku/dealer combo where curdate() < expire_date there should only be x number of rows equal to storefronts

我正试图与拥有10家商店的经销商145进行测试。因此,对于今年curdate()在到期之前的所有记录,如果有意义,每个sku应该不超过10条记录。

$selectRecords = "
    SELECT p.sku_id, p.dealer_id, p.start_date, p.expire_date, p.quantity, s.storefronts, s.dealer_id
        FROM placements p
        inner join storefronts s on p.dealer_id = s.dealer_id
    WHERE p.dealer_id = 145
    and start_date > '2018-01-01'
    order by start_date asc;
";

try{
    $currentRecords = $MysqlConn->prepare($selectRecords);
    $currentResult = $currentRecords->execute();
    $currentCount = $currentRecords->rowCount();
    echo "Open Orders: " . $currentCount . "\n"; //returns correct count
}catch(PDOException $ex){
    echo "QUERY FAILED!: " .$ex->getMessage();
}

$currentArray = [];

while($row = $selectRecords->fetch(PDO::FETCH_ASSOC)){

    //pseudo code
    foreach(sku_id){
        if(rowCount > storefronts){
            delete starting with oldest start_date
            until row count == storefronts
        }
    }
}

我觉得它不应该太复杂,但我真的不知道如何执行这个。

以下是数据示例的小提琴:

http://sqlfiddle.com/#!9/c0dd6

0 个答案:

没有答案