简体   繁体   English

MySQL语句:将行值拆分为新列

[英]MySQL statement: spliting rows values into new columns

Using MySQL I need to return new first/last name columns for each user in table1. 使用MySQL,我需要为table1中的每个用户返回新的名字/姓氏列。

**Table1**  
uid  
1  
2  

**Table2**  
id   fid   uid   field_value  
1    1     1     Joe  
2    2     1     Blow  
3    1     2     Joe  
4    2     2     Blogs

**Result**
uid   first_name   last_name
1     Joe          Blow
2     Joe          Blogs

The solution is simple, 解决方法很简单,

select t1.uid, t21.field_value first_name, t22.field_value last_name
from table1 t1, table2 t21, table2 t22
where t1.uid=t21.uid and t1.uid=t22.uid and t21.fid=1 and t22.fid=2

This should do it (not tested): 应该这样做(未经测试):

select a.uid, a.field_value first_name, b.field_value last_name
from table2 a inner join table2 b on a.uid = b.uid 
where a.fid = 1 and b.fid = 2

假设您在table2中具有first_name和last_name列:

select uid, first_name, last_name from table1 left join table2 on table1.uid=table2.uid

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

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