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