I’m having a problem with MySQL query. I should select members by their age using upper and lower limit to age. For example this query returns some results
SELECT DISTINCT users.*
FROM wp_users as users
INNER JOIN wp_usermeta as mt
ON (users.ID = mt.user_id)
WHERE 1=1
AND (
(mt.meta_key LIKE 'user_birthday' AND mt.meta_value <> '' AND mt.meta_value <= 1985)
AND (mt.meta_key LIKE 'user_birthday' AND mt.meta_value <> '' AND mt.meta_value >= 1920)
)
AND users.ID NOT IN (1,2,3)
ORDER BY users.user_registered desc
This query retuns about 70 results. But when I add search for First name to this query like this:
SELECT DISTINCT users.*
FROM wp_users as users
INNER JOIN wp_usermeta as mt ON (users.ID = mt.user_id)
WHERE 1=1
AND (
(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%first_name::John%')
AND (mt.meta_key LIKE 'user_birthday' AND mt.meta_value <> '' AND mt.meta_value <= 1985)
AND (mt.meta_key LIKE 'user_birthday' AND mt.meta_value <> '' AND mt.meta_value >= 1920)
)
AND users.ID NOT IN (1,2,3)
ORDER BY users.user_registered desc
This returns 0 results, but I know I have 2 Johns in database.
SELECT DISTINCT users.*
FROM wp_users as users
INNER JOIN wp_usermeta as mt ON (users.ID = mt.user_id)
WHERE 1=1 AND (
(mt.meta_key = '_upme_search_cache' AND mt.meta_value LIKE '%first_name::John%')
) AND users.ID NOT IN (1,2,3)
ORDER BY users.user_registered desc
This one returns 2 records.
There are certainly no syntax errors here, but I guess that my logic is off somewhere?
I should mention that this is WordPress database with UPME plugin installed.
Did I make a mistake with joining tables or something else?
The thing is that you’re querying for the data that do not reside in the same row (different values for meta_key column). You need either another JOIN to
wp_usermeta
table, or some sub-query. You can use this fiddle as an illustration of the point http://sqlfiddle.com/#!9/48836/2This may be helpful..