简体   繁体   English

在mysql上将多行合并为一行和多列

[英]Merging multiple rows into one row and multiple columns on mysql

I am working in MYSQL and need to extract user data to be pulled into a view. 我在MYSQL工作,需要提取用户数据以进入视图。 I will be using the data in an email client, so I cannot do this in the app layer. 我将在电子邮件客户端中使用数据,因此我无法在应用层中执行此操作。

The problem is that each data field for the user is contained in separate rows (this is how Wordpress sets up the data structure). 问题是用户的每个数据字段都包含在单独的行中(这就是Wordpress设置数据结构的方式)。

For example, wp_usermeta has multiple rows of data for each user like this: 例如,wp_usermeta为每个用户提供了多行数据,如下所示:

user_id   meta_key       meta_data
   2      first_name     Jane
   2      last_name      Austin
   2      email          jane@me.com
   3      first_name     Jack
   3      last_name      Palmer
   3      email          jack@me.com

I need the data to be combined into one row, separate fields, like this: 我需要将数据合并为一行,单独的字段,如下所示:

user_id  first_name  last_name  email
2        Jane        Austin     jane@email.com
3        Paul        Parker     jack@email.com

I have searched around and cannot find this exact problem anywhere (I found a lot of concatenation, but that is not what I need). 我四处搜索,无法在任何地方找到这个确切的问题(我发现了很多连接,但这不是我需要的)。

If these are the only columns you are concerned with, this will work for you: 如果这些是您唯一关注的列,这将适合您:

SELECT um.user_id
   , fn.meta_data AS first_name
   , ln.meta_data AS last_name
   , e.meta_data AS email
FROM wp_userMeta AS um
LEFT JOIN wp_user_Meta AS fn ON um.user_id = fn.user_id
   AND fn.meta_key = 'first_name'
LEFT JOIN wp_user_Meta AS ln ON um.user_id = ln.user_id
   AND ln.meta_key = 'last_name'
LEFT JOIN wp_user_Meta AS e ON um.user_id = e.user_id
   AND e.meta_key = 'email'

Here is an another solution that doesn't need additional join operations, instead, we make use of group by statement along with case statement. 这是另一个不需要额外连接操作的解决方案,相反,我们使用group by语句和case语句。

select um.user_id,
       max(case when um.meta_key ='first_name' then um.meta_data end) AS first_name,  
       max(case when um.meta_key ='last_name' then um.meta_data end) AS last_name  ,
       max(case when um.meta_key ='email' then um.meta_data end) AS email
from wp_usermeta um 
group by user_id;

Note the max function is just for making them into one row, you can use min as well. 注意max函数只是将它们组成一行,你也可以使用min

Check SQL Fiddler Demo here 在这里检查SQL Fiddler演示

The previous answer and comments give the correct solution. 之前的答案和评论给出了正确的解决方案。 Here is the working query (in schema for WP 3.1) for copy and paste... 这是复制和粘贴的工作查询(在WP 3.1的模式中)...

SELECT distinct u.id, u.user_email,
   fn.meta_value AS first_name,
   ln.meta_value AS last_name
FROM wp_users AS u
LEFT JOIN wp_usermeta AS fn ON u.id = fn.user_id
   AND fn.meta_key = 'first_name'
LEFT JOIN wp_usermeta AS ln ON u.id = ln.user_id
   AND ln.meta_key = 'last_name'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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