SQL Query in WordPress – Getting Impossible WHERE error

Look at your conditions:

WHERE (
  ( 
    (meta_key='user_school_subjects'
      AND meta_value LIKE '%history%')
    OR (meta_key='user_professional_courses'
        AND meta_value LIKE '%history%')
    OR (meta_key='user_language_tutoring'
        AND meta_value LIKE '%history%')
    OR (meta_key='user_music_tutoring'
        AND meta_value LIKE '%history%')
  )
  AND (meta_key='user_gender'
        AND meta_value="male"))

There is no way that you can have a meta key matching one of these–

  • user_school_subjects,
  • user_professional_courses,
  • user_language_tutoring,
  • user_music_tutoring

… that also matches this–

  • user_gender

If the key matches any of the first four, and it has to match one for that block to be true, then it automatically does not match the fifth. You can’t ever get a true out of that. This clause is exactly what the server says– impossible.

I would suggest WP_User_Query but I don’t think it is capable of the logic you need.

You need to JOIN on the table, something like this:

SELECT DISTINCT wpmu.user_id
FROM wp_usermeta AS wpmu
LEFT JOIN wp_usermeta AS gender ON wpmu.user_id = gender.user_id
WHERE (
  (
    (wpmu.meta_key='user_school_subjects'
        AND wpmu.meta_value LIKE '%history%')
      OR (wpmu.meta_key='user_professional_courses'
          AND wpmu.meta_value LIKE '%history%')
      OR (wpmu.meta_key='user_language_tutoring'
          AND wpmu.meta_value LIKE '%history%')
      OR (wpmu.meta_key='user_music_tutoring'
          AND wpmu.meta_value LIKE '%history%')
    )
    AND (gender.meta_key='user_gender'
      AND gender.meta_value="male")
  )

I can’t swear to that 100% since I can’t test it without your data, but that is the idea.