2016-08-24 47 views
1

我有兩個通過用戶ID鏈接的表。我想從兩個表中創建一個新表,從每個表中拉幾個字段。在一個表中,每個用戶ID只有一行,另一個表中的每個用戶有幾行數據。從兩個表中創建一個表,其中數據在一個表中的行中

第一個表很簡單 - 所有的數據都在一行中。
但是,在第二個表中,數據按行排列,其中每個用戶標識具有多行。我想爲每個用戶ID僅查找這些行中的四個,然後將這些行插入到表中的列中。這是下面的代碼,但它不起作用。我可以嵌套這樣的子查詢嗎?

INSERT INTO new_table 
select table1.ID, table1.user_email, table1.display_name, table2.meta-value (where table2.meta_key = ‘pet’), table2.meta-value (where table2.meta_key = ‘color'), table2.meta-value (where table2.meta_key = ‘location), table2.meta-value (where table2.meta_key = ‘house'), 
from table_1, table2 

回答

1

試試這個:

INSERT INTO new_table 
(SELECT 
    t1.ID, 
    t1.user_email, 
    t1.display_name, 
    (SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'pet' AND t2.user_id = t1.user_id), 
    (SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'color' AND t2.user_id = t1.user_id), 
    (SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'location' AND t2.user_id = t1.user_id), 
    (SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'house' AND t2.user_id = t1.user_id), 
    FROM table_1 AS t1 
) 

但是,它沒有經過測試,因爲我沒有找到關於表模式/數據的進一步細節。希望這可以幫助。

1

您可以使用查詢加盟:

INSERT INTO new_table 
select table1.ID, table1.user_email, table1.display_name, table3.meta-value, table4.meta-value, table5.meta-value, table6.meta-value 
from table_1 inner join 
(select ID, meta_value from table2 where meta_key='pet') as table3 inner join 
(select ID, meta_value from table2 where meta_key='color') as table4 inner join 
(select ID, meta_value from table2 where meta_key='location') as table5 inner join 
(select ID, meta_value from table2 where meta_key='house') as table6; 
1
INSERT INTO new_table 
select table1.ID, table1.user_email, table1.display_name, 
     max(if(table2.meta_key = 'pet', table2.meta-value, NULL)), 
     max(if(table2.meta_key = 'color', table2.meta-value, NULL)), 
     max(if(table2.meta_key = 'location', table2.meta-value, NULL)), 
     max(if(table2.meta_key = 'house', table2.meta-value, NULL)) 
from table1 
left join table2 on table2.user_id=table1.user_id 
group by table1.ID, table1.user_email, table1.display_name 
0

我得到它的工作。我不知道這是比其他任何建議好還是差。

INSERT INTO new_table 
SELECT t1.ID, t1.user_email, t1.display_name, 
     GROUP_CONCAT(IF(m.meta_key = 'pet_field', m.meta_value, NULL)) AS pet, 
     GROUP_CONCAT(IF(m.meta_key = 'color_field', m.meta_value, NULL)) AS color, 
     GROUP_CONCAT(IF(m.meta_key = 'location_field', m.meta_value, NULL)) AS location, 
     GROUP_CONCAT(IF(m.meta_key = 'house_field', m.meta_value, NULL)) AS house 
FROM wp_users t1, 
     wp_usermeta m 
WHERE u.ID = m.user_id 
GROUP BY u.ID; 
相關問題