简体   繁体   中英

How to get multiple same fields on one single field in same table using SQL Query

Example table 'meta_data':

| user_id | meta_id | meta_value
| ------- | ------- | ----------
| 1       | 11      | abc
| 1       | 12      | xyz

Output:

| user_id | meta_id | meta_value11 | meta_value12
| ------- | ------- | ------------ | ------------
| 1       | 11      | abc          |
| 1       | 12      |              | xyz

My Query:

select user_id,meta_value11,meta_value12 
from meta_data 
where user_id = 1 and (meta_id = 11 or meta_id = 12)
select user_id,meta_id,(case when meta_id = 11 then meta_value else '' end) as meta_value11, (case when meta_id = 12 then meta_value else '' end) as meta_value12 from meta_data where user_id =1;

You can use above query for your task which use case statements.Better if use null than use '' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM