简体   繁体   中英

MySQL insert into table by id from another table

I have 3 tables and I'm trying to add a new row in phone_info table for each user_id in user_info table

表格图

I've tried several queries but none of them work:

INSERT INTO phone_info(phone_name, phone_number) VALUES ('phone1', '7687')
JOIN userplans ON (phone_info.userplans_userplan_id = userplans.userplan_id)
JOIN user_info ON (userplans.user_info_user_id = user_info.user_id)
WHERE user_info.user_id = 3

and

INSERT INTO phone_info (phone_name, phone_number) 
SELECT  'phone1', '7687'
FROM user_info
WHERE user_info.user_id = 3

Thank you!

Iz is very unclear where ypou phonenumber and phonename are coming from

The query would add a static text for every unique user_inofo_user_id

INSERT INTO phone_info(phone_name, phone_number,userplans_userpkan_id) 
SELECT  MAX('phone1'), MAX('7687'),MAX(userplan_id) FROM userplans GROUP BY user_inofo_user_id

Use

INSERT INTO phone_info(phone_name, phone_number,userplans_userplan_id)
SELECT 'phone1', '7687',up.userplan_id
FROM userplans up
WHERE up.user_info_user_id = 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM