MySQL Insert Into Table From Multiple Tables Using Separate SELECT Queries

前端 未结 3 1739
误落风尘
误落风尘 2021-01-07 05:04

I have a table named people_temp_1 that contains:

Name          Age          PersonID
John          25           1
Jane          32           2
Chris                 


        
相关标签:
3条回答
  • Try to use join syntax as below

    INSERT INTO people(name, age, profession, location)
    SELECT p1.namename,
    p2.age,
    p2.profession,
    p2.location
    FROM people_temp_1 p1
    JOIN people_temp_2 p2 on p2.id = p1.personId
    

    More information about joins on mysql

    0 讨论(0)
  • 2021-01-07 05:32

    Use a JOIN.

    INSERT INTO people(name, age, profession, location)
    SELECT t1.name, t1.age, t2.profession, t2.location
    FROM people_temp_1 t1
    INNER JOIN people_temp_2 t2
    ON t1.personid = t2.id
    
    0 讨论(0)
  • 2021-01-07 05:38

    It's one of the basics of SQL - use join. In your case it's better to use outer join so you won't miss people from people_temp1 who don't have corresponding records in people_temp2:

    insert into people(name, age, profession, location)
    select
        p1.name,
        p1.age
        p2.profession,
        p2.location
    from people_temp1 as p1
        left outer join people_temp2 as p2 on p2.id = p1.person_id
    
    0 讨论(0)
提交回复
热议问题