2017-10-12 146 views
0

我的問題是 我想查詢從tbl_one和遍歷結果x行和值插入另一個表查詢插入每個記錄

select id as user_id, p_id from users where b_id = 0 // this will give me let's say 10 rows 

現在我想要使​​用每一行插入到地址表中,如

insert into addresses (user_id, passenger_id, address_type, address_line1, city, country) value (user_id, passenger_id, 'Test street address', 'XXX', "XX") 

我該如何在mysql中執行此操作。嘗試從https://dev.mysql.com/doc/refman/5.7/en/loop.html的mysql文檔搜索,但那裏解釋的循環邏輯是非常靜態的,我不明白。

+0

你會在哪裏得到的值其他欄目:address_type,address_line1,城市,國家? – Lamar

+0

我想讓它們保持靜態,如查詢 – Gunnrryy

+0

中所述在這種情況下檢查我的答案。 – Lamar

回答

0

使用INSERT INTO SELECT語句:

INSERT INTO addresses (user_id, passenger_id, address_type, address_line1, city, country) 
SELECT id, p_id, address_type, 'Test street address', 'XXX', 'XX') 
FROM users 
WHERE b_id = 0 
0

如果你想保持對其他colums像address_type等靜態,那麼你可以使用下面的查詢:

INSERT INTO addresses (user_id, passenger_id, address_type, address_line1, city, country) 
SELECT id, p_id, "Test Address Type", 'Test Address', 'Test City', 'Test Country') 
FROM users 
WHERE b_id = 0 
相關問題