Reputation: 1417
I have got a SQL query to get data from my MySQL database:
SELECT wp_users.ID, wp_users.time, wp_users.display_name
FROM wp_users
INNER JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id
WHERE wp_usermeta.meta_key = 'wp_capabilities'
AND wp_usermeta.meta_value LIKE '%user%'
AND wp_users.time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MINUTE))
ORDER BY wp_users.display_name";
It is getting a list of all users without the second AND statement:
AND wp_users.time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MINUTE))
Is there anything I can do to have two ANDs to make it working?
Many thanks in advance
Upvotes: 0
Views: 65
Reputation: 346
I don't see an error with the query. I think the error is an artefact of your data set. From the comments on your question, I understand that the original query:
SELECT wp_users.ID, wp_users.time, wp_users.display_name
FROM wp_users
INNER JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id
WHERE wp_usermeta.meta_key = 'wp_capabilities'
AND wp_usermeta.meta_value LIKE '%user%'
AND wp_users.time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MINUTE))
ORDER BY wp_users.display_name";
returns no results, but that removing the inner join and join conditions:
SELECT wp_users.ID, wp_users.time, wp_users.display_name
FROM wp_users
WHERE wp_users.time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MINUTE))
ORDER BY wp_users.display_name";
produces what you were expecting. This implies that:
Inner joins require matching key entries: http://www.w3schools.com/sql/sql_join_inner.asp
I think your choices are:
SELECT wp_users.ID, wp_users.time, wp_users.display_name
FROM wp_users
LEFT JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id
ON wp_usermeta.meta_key = 'wp_capabilities'
AND wp_usermeta.meta_value LIKE '%user%'
WHERE wp_users.time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MINUTE))
ORDER BY wp_users.display_name;
That will technically make it work, but your query will be accepting users who only have NULLs for the corresponding (non-participating) wp_usermeta entries.
Upvotes: 2