0

We started with one table for a project and soon realized we needed multiple tables for what we wanted to do.

We started to switch over, but now I want to get completely switched from one table to multiple.

What I have now:

TABLE: CONTACT
+-----+-------+--------+----------+
| id  | fname | lname  | phone    |
+-----+-------+--------+----------+
| 123 | John  | Doe    | 555-1234 |
| 124 | Mary  | Shelly | 555-5857 |
| 125 | Jane  | Doe    | NULL     |
+-----+-------+--------+----------+

TABLE: PHONE
+----+--------+----------+------+
| id | con_id |   phone  | main |
+----+--------+----------+------+
| 1  | 125    | 555-5857 | N    |
+----+--------+----------+------+

So we have a few that were added and changed. Now, I need to add all the data that isn't already in the PHONE table from the CONTACT table. I do that with a temp table:

TABLE: temp
+------------+----------+------+
| foreign_id |   phone  | main |
+------------+----------+------+
| 123        | 555-1234 | Y    |
| 124        | 555-4153 | Y    |
| 125        | 555-5857 | N    |
+------------+----------+------+

But when I add from temp to phone, I end up with duplicate entries (in the example, where contact.id = 125).

This is what I am trying to get to:

TABLE: CONTACT
+-----+-------+--------+
| id  | fname | lname  |
+-----+-------+--------+
| 123 | John  | Doe    |
| 124 | Mary  | Shelly |
| 125 | Jane  | Doe    |
+-----+-------+--------+


TABLE: PHONE
+----+--------+----------+------+
| id | con_id |   phone  | main |
+----+--------+----------+------+
| 1  | 125    | 555-5857 | N    |
| 2  | 123    | 555-1234 | Y    |
| 3  | 124    | 555-4153 | Y    |
+----+--------+----------+------+

Commands I've run:

create temporary table temp (select t2.id, phone from contact t2);
alter table temp add main varchar(1);
update temp set main = "Y";

insert into phone (con_id, phone, main) select id, phone, main from temp;
drop table temp;

And eventually, I'll remove the column "phone" from contact. Problem is, if there is already an entry in the table for a phone number, I'm left with duplicates. How do I prevent that?

Also, if I'm doing it wrong, I can change that too. I just figured a temp table might be the best way?

4

1 回答 1

2

您可以通过向电话表添加主键(或唯一键)来避免重复:

ALTER TABLE phone ADD PRIMARY KEY (con_id);

这将确保每个 con_id 只有一个条目。如果你想为每个 con_id 允许多个电话号码,你应该使用:

ALTER TABLE phone ADD PRIMARY KEY (con_id, phone);

现在,您可以直接从联系人表中插入条目 - 或者如果您已经在联系人表中删除了电话列,则可以从临时表中插入条目:

REPLACE INTO phone (con_id,phone,main) 
   SELECT id, phone, "Y" FROM contact;

或者,您可以使用 INSERT ... ON DUPLICATE KEY UPDATE ... 构造。如果您不想覆盖但保留原始的非主键值,则可以使用 INSERT IGNORE 代替。

有关 INSERT 语法的更多详细信息,请参阅:http ://docs.oracle.com/cd/E17952_01/refman-5.1-en/insert.html

于 2013-07-17T17:06:43.227 回答