使用MySQL我需要为table1中的每个用户返回新的名/姓列。MySQL语句:将行值拆分为新列
**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
使用MySQL我需要为table1中的每个用户返回新的名/姓列。MySQL语句:将行值拆分为新列
**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
解决方法很简单,
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
谢谢你做到了! – EddyR 2009-09-17 09:23:29
假设你有列FIRST_NAME和姓氏在表2:
select uid, first_name, last_name from table1 left join table2 on table1.uid=table2.uid
这应该这样做(未测试):
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
请小心使用此方法。要提取的字段越多,需要的联接就越多。 MySQL中的大连接费用很高。尽管拥有所有指数并被缓存,但每个连接30K行的3张表格可能需要1-5分钟。 – 2009-09-17 09:03:13