简体   繁体   中英

SELECT different values on same Column

I'm trying to get a HTML table with:

User's first name | User's last name | Phone | Product he bought

And I have the next table (made automatically with Woocommerce):

meta_id  |  post_id  |  meta_key  |  meta_value

   100         41        email      email@example
   101         41        phone       666666666
   102         41       firstname       Name
   103         41       lastname       Lastname

How can I SELECT the values email, phone, first name and last name with just one query, to "echo" it on my PHP file. Tried with UNION, with a SELECT in the first SELECT... and they don't output what i want.

Thanks!!

One method is using conditional aggregation:

select post_id,
       max(case when meta_key = 'firstname' then meta_value end) as firstname,
       max(case when meta_key = 'lastname' then meta_value end) as lastname,
       max(case when meta_key = 'phone' then meta_value end) as phone,
       max(case when meta_key = 'email' then meta_value end) as email
from t
group by post_id;

Conditional aggregation makes it really easy to add new columns or to concatenate together value when keys are repeated (hint: use group_concat() ).

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