我的WP_Users表中有超过50,000个注册用户。通常我需要运行查询来检查和统计我的用户的不同状态。
我经常写下面的内容。
$users = get_users(); //This query is not limited I need to run across all my users.
$active_users = 0;
foreach ($users as $user) {
$last_transaction_date = strtotime(get_user_meta($user_id, 'last_trans_date', true));
$next_recurring_date = strtotime(get_user_meta($user_id, 'next_recurring_date', true));
$todays_date = strtotime('now');
if ($todays_date >= $last_transaction_date && $todays_date <= $next_recurring_date ) {
$active_users++;
}
}
这个问题是它为每个用户生成2个数据库调用,因此速度极慢,容易导致崩溃。有没有人有建议?
答案 0 :(得分:0)
您应该只对wp_usermeta表执行两次查询 像这样
STEP1
$SQLresult1 = $wpdb->get_results("
SELECT user_id, meta_value
FROM wp_usermeta
WHERE meta_key = 'last_trans_date'
AND $todays_date >= meta_value
");
//convert it to array
SQLarr1 = [];
foreach ($SQLresult1 as &$item) {
SQLarr1[$item->user_id] = $item->meta_value
}
STEP2
$SQLresult2 = $wpdb->get_results("
SELECT user_id, meta_value
FROM wp_usermeta
WHERE meta_key = 'next_recurring_date'
AND $todays_date <= meta_value
");
//convert it to array
SQLarr2 = [];
foreach ($SQLresul2 as &$item) {
SQLarr2[$item->user_id] = $item->meta_value
}
STEP3
$active_users = 0;
foreach ($SQLarr1 as $user_id => &$item) {
if (isset($SQLarr2[$user_id]))
$active_users++;
}
我没有查看此代码。但你可以看到主要想法