[英]Combine Two Rows in MySQL to Show Data as One Row
I want to join WooCommerce created post meta fields to show first and last name of client together in one row. 我想加入WooCommerce创建的发布元字段,以在一行中一起显示客户的名字和姓氏。
The table structure of mysql is as follow: mysql的表结构如下:
meta_id post_id meta_key meta_value
======= ======= ======= ===========
1234 1874 _billing_first_name John
1235 1874 _billing_last_name Cobe
Now I want it to return following results using mysql statement 现在我希望它使用mysql语句返回以下结果
post_id _billing_first_name _billing_last_name
======= ==================== ==================
1874 John Cobe
Looking forward to your suggestions and help. 期待您的建议和帮助。
Thanks. 谢谢。
If you have two fixed values for meta_key, you can use something like this: 如果meta_key有两个固定值,则可以使用如下所示的内容:
SELECT
post_id,
MAX(CASE WHEN meta_key='_billing_first_name' THEN meta_value END) _billing_first_name,
MAX(CASE WHEN meta_key='_billing_last_name' THEN meta_value END) _billing_last_name
FROM
yourtable
GROUP BY
post_id
Take a look at the PIVOT function. 看一下PIVOT功能。 I think it will work perfectly for you. 我认为它将完全适合您。
Here is an example in SQL Fiddle 这是SQL Fiddle中的示例
SELECT * FROM ( SELECT post_id, meta_key, meta_value FROM table_name WHERE post_id = 1874 ) as x PIVOT ( MAX(meta_value) FOR meta_key IN ([_billing_first_name], [_billing_last_name]) ) as p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.