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

时间:2009-09-17 08:14:32

标签: mysql

使用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

3 个答案:

答案 0 :(得分:2)

解决方案很简单,

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

答案 1 :(得分:0)

这应该做(未经测试):

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

答案 2 :(得分:-1)

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

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