Currently I am working on a WordPress site, and I would like it to be possible to search for users on their first and last name on a part of my site.
WordPress makes use of a meta table to store any ‘extra’ data for a user. And the first and last name are some of those meta fields.
Now I am trying to create a query which gets me a result which returns me a user matching the first and last name, the only problem is that there is a meta row for last name and another one for first-name, they both do have a reference to the same user_id. Only I don’t know how I can create the query correctly.
When I have this query
SELECT U.id FROM wp_users AS U, wp_usermeta as US
WHERE U.id=US.user_id
AND (US.meta_key='first_name' AND US.meta_value='MyFirstName')
It does return the user I am looking for, however when I try this
SELECT U.id FROM wp_users AS U, wp_usermeta as US
WHERE U.id=US.user_id
AND (US.meta_key='first_name' AND US.meta_value='MyFirstName')
AND (US.meta_key='last_name' AND US.meta_value='Dijkstra')
I get no results at all, could someone help me?
In case someone is interested in the database structure, here ( http://cl.ly/6rGx ) is the users table and here ( http://cl.ly/6rts ) is the users_meta table.
Thanks in advance
You can’t join one row to two other rows of another table at the same time, so you need to join the other table twice, once for first name and once for last name. Like this: