1

试图检索那些 user_id 满足 3 个条件的所有 user_id。

我的代码是

$sql = "
SELECT user_id
FROM {$wpdb->usermeta} 
WHERE (({$wpdb->usermeta}.meta_key = 'job_title' AND {$wpdb-
>usermeta}.meta_value = '".$job_title."') OR
({$wpdb->usermeta}.meta_key = 'pmpro_bstate' AND {$wpdb-
>usermeta}.meta_value = '".$state."') OR
({$wpdb->usermeta}.meta_key = 'pmpro_baddress2' AND {$wpdb-
>usermeta}.meta_value = '".$suburb."'))
GROUP BY
   user_id
HAVING 
   COUNT(DISTINCT meta_key)=3";

值和变量是否需要 Lower() 才能准确比较它们?

有没有更有效的方法来执行这个查询?

干杯

4

1 回答 1

1

使用 INNER JOIN 执行此操作要好得多:

$sql = "SELECT u.ID
FROM wp_users u
INNER JOIN wp_usermeta m1 ON u.ID = m1.user_id AND m1.meta_key = 'job_title'
INNER JOIN wp_usermeta m2 ON u.ID = m2.user_id AND m2.meta_key = 'pmpro_bstate'
INNER JOIN wp_usermeta m3 ON u.ID = m3.user_id AND m3.meta_key = 'pmpro_baddress2'
WHERE m1.meta_value = '".$job_title."'
AND m2.meta_value = '".$state."'
AND m3.meta_value = '".$suburb."'"
于 2017-08-28T09:33:39.087 回答