首页 > 解决方案 > 确保最新数据在 SQL 查询中优先

问题描述

我在底部有一个带有以下查询的循环,它将列值更改为updated_in_sib匹配1customer_id

$wpdb->update('imp_customer_log', ['updated_in_sib' => 1], ['customer_id' => $customer_id]);

这是我的数据库设置:

CREATE TABLE `imp_customer_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` varchar(128) DEFAULT NULL,
  `event` varchar(128) DEFAULT NULL,
  `data` varchar(128) DEFAULT NULL,
  `updated_in_sib` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=74 DEFAULT CHARSET=latin1

目前正在添加行(同一数据可以有多行),但查询选择了最旧的id行,因此当使用新数据添加新行时,它会被忽略。

如何选择最新的行?

例如,id72 行中的数据被用于 73 行id,73 显然是较新的数据。

在某些情况下,这是我遍历每一行的完整代码:

// Update SiB contact hourly
function sendinblue_update() {
  global $wpdb;

  $customer_data = $wpdb->get_results("SELECT * FROM imp_customer_log WHERE updated_in_sib = '0'");
    foreach( $customer_data as $customer ) {

        $customer_id = $customer->customer_id;
    $customer_event = $customer->event;
    $customer_data = $customer->data;

        $user = get_user_by( 'id', $customer_id );
        $user_email = $user->user_email;

        $data_in = array(
            $customer_event => $customer_data,
        );
        $result = $this->sendinblue_update_user($user_email, $data_in);

        $wpdb->update('imp_customer_log', ['updated_in_sib' => 1], ['customer_id' => $customer_id]);

  }

}

标签: phpsql

解决方案


select * from imp_customer_log icl where icl.customer_id = 'xxx' 
and icl.id = (select max(icl2.id) from imp_customer_log icl2 where icl2.customer_id = 'xxx')

或者

select max(id) from imp_customer_log where customer_id = xxx

考虑到 id 是自动递增的,这将始终为您提供最新的行


推荐阅读