MySQL single statement to merge two tables

前端 未结 5 942
傲寒
傲寒 2021-01-24 04:01

I\'m sure this has been ask/answered already but I don\'t know how this kind of action is called and my SQL knowledge is limited.

I\'m searching for a single SQL statem

5条回答
  •  我在风中等你
    2021-01-24 04:43

    You can do this with a join and a group by:

    select u.*, firstname, lastname
    from user u join
         (select uf.user_id,
                 max(case when key = 'firstname' then value end) as firstname,
                 max(case when key = 'lastname' then value end) as lastname
          from user_field uf
          group by user_id
         ) uf
         on uf.user_id = u.id;
    

    You can also do this with a sequence of joins:

    select u.*. firstname.value, lastname.value
    from user u join
         user_field firstname
         on u.id = firstname.user_id and firstname.key = 'firstname' join
         user_field lastname
         on u.id = lastname.user_id and lastname.key = 'lastname';
    

    Your result seems to limit this to just one user id. You might want a where clause with this filter.

提交回复
热议问题