0

I have a table in MySQL which looks like this.

+---------+------------+--------------+
| user_id |    key     |     value    |
+---------+------------+--------------+
|    1    | full_name  |  John Smith  |
+---------+------------+--------------+
|    1    | is_active  |      1       |
+---------+------------+--------------+
|    1    | user_level |Administrator |
+---------+------------+--------------+

I need to get value of key full_name where user_id is 1, but only if value of key is_active is 1. I can do it with 2 separate queries, but I would like to know if it is possible to do it in a single query.

Note: I cannot change the structure of the table.

2 Answers 2

3

One method is to use joins:

select tn.value
from t tn join
     t ta
     on tn.user_id = ta.user_id and ta.key = 'active'
where tn.key = 'fullname';
Sign up to request clarification or add additional context in comments.

Comments

1

i think you need below query by using exists

select t.value from your_table t where 
exists ( select 1 from your_table t1
         where t1.user_id=t.user_id 
         and t1.key='is_active'
       ) and t.key='full_name'

DEMO IN MYSQL 8

 value
john smith

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.