'How to select meta value column based on user id and two meta keys

I want to select values 'b' and 'c' by meta key and user id = 197

select issue

Select cc.meta_value, fname,cc.meta_value lname FROM usermeta cc where 
user_id = 197 and (cc.meta_key = 'last_name' or cc.meta_key = 'first_name')


Solution 1:[1]

You could use the second condition in the WHERE clause to achieve what you want. It's important to wrap the second condition inside parentheses. Like this:

SELECT * 
FROM wp_usermeta 
WHERE user_id = 1 
AND 
(
CONVERT(meta_key USING utf8) = 'first_name' 
OR
CONVERT(meta_key USING utf8) = 'last_name'
)

Which outputs this:

enter image description here


If you only need the meta_value column, then you could use this:

SELECT meta_value 
FROM wp_usermeta 
WHERE user_id = 1 
AND 
(
CONVERT(meta_key USING utf8) = 'first_name' 
OR
CONVERT(meta_key USING utf8) = 'last_name'
)

Which outputs this:

enter image description here

Solution 2:[2]

If You want to select them in one query:

select meta_value from YOURTABLENAME where user_id=197 
and meta_key in ('first_name','last_name')

Or if You want to select them separately:

select meta_value from YOURTABLENAME where user_id=197 and meta_key='last_name';
select meta_value from YOURTABLENAME where user_id=197 and meta_key='first_name';

Solution 3:[3]

Try this:

In will get you all the values in the specified list

Select cc.meta_value fname,cc.meta_value lname 
FROM usermeta cc where 
user_id = 197 and cc.meta_key in('last_name','first_name')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ruvee
Solution 2 VKU
Solution 3 Moulitharan M