2

我有一个名为 people_temp_1 的表,其中包含:

Name          Age          PersonID
John          25           1
Jane          32           2
Chris         47           3

另一个名为 people_temp_2 的文件包含由 table1 中的 PersonID 链接的附加信息:

ID          Profession          Location
1           Web Developer       Texas
2           Graphic Designer    North Carolina
3           Sales               California

我想创建一个名为 people 的新表,它“合并”两个表中的数据。我现在的做法是:

INSERT INTO people(name, age, profession, location)
SELECT people_temp_1.name AS name,
people_temp_2.age AS age,
(SELECT people_temp_2.profession FROM people_temp_2 WHERE people_temp_2.id = people_temp_1.personId) AS profession,
(SELECT people_temp_2.location FROM people_temp_2 WHERE people_temp_2.id = people_temp_1.personId) AS location
FROM people_temp_1

如您所见,我在插入查询中使用了多个选择查询,以便通过 personId 获取相关数据。当我应该能够以某种方式查询 people_temp_2 表并使用它的所有列时,执行多个选择查询似乎有点脏,但我不知道该怎么做。

有没有更好的方法来构造插入语句?

4

3 回答 3

4

它是 SQL 的基础之一 - 使用join。在您的情况下,最好使用outer join,这样您就不会错过people_temp1没有相应记录的人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
于 2013-08-24T14:05:47.547 回答
0

尝试使用如下连接语法

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

有关 mysql 上的连接的更多信息

于 2013-08-24T14:05:50.733 回答
0

使用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
于 2013-08-24T14:06:48.063 回答