简体   繁体   English

将多行合并为一行MySQL,并在同一查询中将值从一个字段拆分为两个

[英]Combine multiple rows into one row MySQL and split value from one field to two in same Query

I'm kind of new to MySQL but I've managed to find the individual solutions to two things I was trying to do, now I just need help combining them. 我是MySQL的新手,但是我设法找到了我要尝试做的两件事的个别解决方案,现在我只需要将它们组合在一起的帮助即可。

I have a database with a two tables: Users and user_profile. 我有一个包含两个表的数据库:Users和user_profile。 I have managed to create a query that combines data from both tables into a single table with the following: 我设法创建了一个查询,该查询将两个表中的数据合并到一个表中,并具有以下内容:

select t1.id,
  t1.name,
  max(case when t2.`profile_key` = 'profile.address1' then t2.profile_value end) address,
  max(case when t2.`profile_key` = 'profile.city' then t2.profile_value end) city,
  max(case when t2.`profile_key` = 'profile.postal_code' then t2.profile_value end) postal_code,
  max(case when t2.`profile_key` = 'profile.phone' then t2.profile_value end) phone
from users t1
left join user_profiles t2
  on t1.id = t2.user_id
group by t1.id, t1.name

I would also like to split the "name" column into "first name" and "last name" so that I can sort by last name. 我还想将“名称”列分为“名字”和“姓氏”,以便我可以按姓氏排序。 I can accomplish that with this: 我可以做到这一点:

SELECT IF(
        LOCATE(' ', `name`) > 0,
        SUBSTRING(`name`, 1, LOCATE(' ', `name`) - 1),
        `name`
    ) AS memberfirst,
    IF(
        LOCATE(' ', `name`) > 0,
        SUBSTRING(`name`, LOCATE(' ', `name`) + 1),
        NULL
    ) AS memberlast
FROM `users`;

Is there a way to combine these quires into one? 有没有办法将这些需求组合成一个?

UNION SELECT,row1_name,row2_name,FROM tbl_name应该可以解决问题,不记得语法是否正确,但查询是union :)

I think I understand that you want the first and last name instead of just the name, so try this: 我想我知道您想要名字和姓氏,而不仅仅是名字,所以请尝试以下操作:

SELECT t1.id,
IF(
    LOCATE(' ', t1.name) > 0,
    SUBSTRING(t1.name, 1, LOCATE(' ', t1.name) - 1),
    t1.name
    ) AS memberfirst,
    IF(
    LOCATE(' ', t1.name) > 0,
    SUBSTRING(t1.name, LOCATE(' ', t1.name) + 1),
    NULL
    ) AS memberlast , 
  MAX(CASE WHEN t2.`profile_key` = 'profile.address1' THEN t2.profile_value END) address,
  MAX(CASE WHEN t2.`profile_key` = 'profile.city' THEN t2.profile_value END) city,
  MAX(CASE WHEN t2.`profile_key` = 'profile.postal_code' THEN t2.profile_value END) postal_code,
  MAX(CASE WHEN t2.`profile_key` = 'profile.phone' THEN t2.profile_value END) phone
FROM users t1
LEFT JOIN user_profiles t2
  ON t1.id = t2.user_id
GROUP BY t1.id, t1.name

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

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