简体   繁体   中英

MYSQL Create table with Unique values

I am trying to UPDATE my table from another table. I would like to ignore duplicates and also delete any matches in that table.

Source Table          Table 1              Table 2
Customer | Address    Customer | Address   Customer | Address
__________________    __________________   __________________

Mike      123 Main    Mike      123 Main     Bob      999 1st 
Steve     456 Maple   Steve     456 Maple
John      789 Elm     John      789 Elm
Bob       999 1st

For example, Table 2 will only have the unique entry after "Source Table" is compared to Table 1. I am using MYSQL/PHP.

Any direction is greatly appreciated.

SQL Fiddle

MySQL 5.5.32 Schema Setup :

CREATE TABLE Source
    (`Customer` varchar(5), `Address` varchar(9))
;

INSERT INTO Source
    (`Customer`, `Address`)
VALUES
    ('Mike', '123 Main'),
    ('Steve', '456 Maple'),
    ('John', '789 Elm'),
    ('Bob', '999 1st'),
    ('Bob', '999 1st')
;

CREATE TABLE Table1
    (`Customer` varchar(5), `Address` varchar(9))
;

INSERT INTO Table1
    (`Customer`, `Address`)
VALUES
    ('Mike', '123 Main'),
    ('Steve', '456 Maple'),
    ('John', '789 Elm')
;

CREATE TABLE Table2
    (`Customer` varchar(5), `Address` varchar(9))
;

DELETE FROM Table2;
INSERT INTO Table2
    (`Customer`, `Address`)
SELECT DISTINCT Customer, Address
FROM Source
WHERE NOT EXISTS (SELECT 1 FROM Table1 WHERE Source.Customer = Table1.Customer)

Query 1 :

SELECT *
FROM Table2

Results :

| CUSTOMER | ADDRESS |
|----------|---------|
|      Bob | 999 1st |

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