插入另一个 table 共享给定值的第一行的 ID,以及每个重复行中的另一个值
Inserting into another table the id of the first row sharing given values, and another value from each duplicate row
对不起标题 - 我很难用简洁的措辞表达它
所以我有一些数据目前全部集中在一个 table 中,我想将其存储在两个不同的 table 中。这是我的情况的简单版本:
Person:
+----+-----------+----------+----------+
| Id | FirstName | LastName | City |
+----+-----------+----------+----------+
| 1 | Billy | Bob | Toronto |
| 2 | Billy | Bob | Mumbai |
| 3 | Sally | Ann | Toronto |
| 4 | Joe | Hall | New York |
| 5 | Joe | Hall | Boston |
+----+-----------+----------+----------+
所以我有一群人和他们的城市。我想这样做 first/last 名称的给定组合只出现一次,第二个 table 描述名称 id <-> 城市组合,如下所示:
Person:
+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
| 1 | Billy | Bob |
| 3 | Sally | Ann |
| 4 | Joe | Hall |
+----+-----------+----------+
LivesIn:
+----------+----------+
| PersonId | City |
+----------+----------+
| 1 | Toronto |
| 1 | Mumbai |
| 3 | Toronto |
| 4 | New York |
| 4 | Boston |
+----------+----------+
我的问题是:我如何 select 仅将每个名称组合的第一个实例插入到第二个 table 中?要准确移动数据,我可以这样做:
INSERT INTO LivesIn (PersonId, City)
SELECT Id, City
FROM Person
但这意味着 LivesIn
仍然会有两个不同的 PersonId
同名组合。
INSERT INTO LivesIn (PersonId, City)
select t1.id, t2.City
from
(
SELECT min(Id) as id, FirstName, LastName
FROM Person
GROUP BY FirstName, LastName
) t1
join person t2 on t1.FirstName = t2.FirstName
and t1.LastName = t2.LastName
对不起标题 - 我很难用简洁的措辞表达它
所以我有一些数据目前全部集中在一个 table 中,我想将其存储在两个不同的 table 中。这是我的情况的简单版本:
Person:
+----+-----------+----------+----------+
| Id | FirstName | LastName | City |
+----+-----------+----------+----------+
| 1 | Billy | Bob | Toronto |
| 2 | Billy | Bob | Mumbai |
| 3 | Sally | Ann | Toronto |
| 4 | Joe | Hall | New York |
| 5 | Joe | Hall | Boston |
+----+-----------+----------+----------+
所以我有一群人和他们的城市。我想这样做 first/last 名称的给定组合只出现一次,第二个 table 描述名称 id <-> 城市组合,如下所示:
Person:
+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
| 1 | Billy | Bob |
| 3 | Sally | Ann |
| 4 | Joe | Hall |
+----+-----------+----------+
LivesIn:
+----------+----------+
| PersonId | City |
+----------+----------+
| 1 | Toronto |
| 1 | Mumbai |
| 3 | Toronto |
| 4 | New York |
| 4 | Boston |
+----------+----------+
我的问题是:我如何 select 仅将每个名称组合的第一个实例插入到第二个 table 中?要准确移动数据,我可以这样做:
INSERT INTO LivesIn (PersonId, City)
SELECT Id, City
FROM Person
但这意味着 LivesIn
仍然会有两个不同的 PersonId
同名组合。
INSERT INTO LivesIn (PersonId, City)
select t1.id, t2.City
from
(
SELECT min(Id) as id, FirstName, LastName
FROM Person
GROUP BY FirstName, LastName
) t1
join person t2 on t1.FirstName = t2.FirstName
and t1.LastName = t2.LastName