简体   繁体   中英

SQL create new row with values unless row with 2 columns match

I create my table by doing so:

CREATE TABLE IF NOT EXISTS table_name (uuid VARCHAR(128), item VARCHAR(48), value FLOAT(11))

When I insert values, I want UUID and ITEM together to unique. By that I mean, if there is an entry where uuid and item matches the new values, it will update that one. If not, it will create a new one. So I don't want UUID to have a unqiue key, nor ITEM. But I sorta want them to become unique together. So there can't be 2 entries where both UUID and ITEM match the other entry's UUID and ITEM.

If my explanation wasn't awful, does anyone know how that could be done?

Is this what you're looking for? First make uuid and item your primary key.

CREATE TABLE IF NOT EXISTS table_name (uuid VARCHAR(128), item VARCHAR(48), value FLOAT(11), PRIMARY KEY(uuid, item)) ENGINE InnoDB;

Then use, "ON DUPLICATE UPDATE"

INSERT INTO table_name(UUID, item, value)
VALUES ('315c383c-b977-11e4-a6d1-954287e1d27a',  'item1', 1.0)
ON DUPLICATE KEY UPDATE value = VALUES(value);

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html Insert into a MySQL table or update if exists

Try something like this.

To insert the rows only if it is a new combination

INSERT INTO table_name
SELECT uuid,
       item,
       value
FROM   source_table S
WHERE  NOT EXISTS (SELECT 1
                   FROM   table_name T
                   WHERE  S.uuid = T.uuid
                          AND s.item = t.item)

To update the rows if the combination already exists

UPDATE table_name T
       JOIN source_table S
         ON S.uuid = T.uuid
            AND s.item = t.item
SET    T.value = S.value 

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