php - 确保最新数据在 SQL 查询中优先
问题描述
我在底部有一个带有以下查询的循环,它将列值更改为updated_in_sib
匹配1
时customer_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
行,因此当使用新数据添加新行时,它会被忽略。
如何选择最新的行?
例如,id
72 行中的数据被用于 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]);
}
}
解决方案
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 是自动递增的,这将始终为您提供最新的行
推荐阅读
- ios - 缓存多少?
- javascript - 选择 react-router (React) 时的 setState
- c++ - 使用 min(a,b) 和 max(a,b) 比较并显示 4 个升序数字
- batch-file - 在批处理脚本中将带或不带空格的文件路径传递给cygwin ..“'\混淆
- windows - 在 Windows 的 gitbash 中运行 bigquery
- rust - 为类型参数传达 Rust 生命周期
- server - httpd.conf 文件不包含“订单拒绝,允许”的行
- angular - 在 ngOnInit 而不是在 Angular 的 Constructor 中定义服务的好处
- typo3 - 如何在 TYPO3 v9 URL 中添加斜杠?
- octave - 来自 fminunc 函数的未定义参数错误