开发者

MySQL Join with Insert combined?

开发者 https://www.devze.com 2023-03-23 19:47 出处:网络
Is it possible to have an INSERT from a reference tab开发者_开发知识库le if something exists there?

Is it possible to have an INSERT from a reference tab开发者_开发知识库le if something exists there?

Say this is the query to insert some data...

INSERT INTO  `Test`.`Items` (
`Name` ,
`Type` ,
`Number`
)
VALUES (
'Pork',  'Sausage', 6
);

And that I have a lookup table called "Lookup" that contains two columns. "Type" and "Number". What I want is that if something exists in the "Lookup" table in this instance for Type Sausage then to pull in the "Number" field from the lookup table instead of inserting the 6 in the INSERT statement.

MySQL Join with Insert combined?

Hope that is clear!


INSERT INTO Test.Items 
    (Name, Type, Number)
    SELECT 'Pork', 'Sausage', COALESCE(l.Number, 6)
        FROM Lookup l
        WHERE l.Type = 'Sausage'

EDIT: Additional samples based on comments below.

Using UNION ALL to string inserts together:

INSERT INTO Test.Items 
    (Name, Type, Number)
    SELECT 'Pork', 'Sausage', COALESCE(l.Number, 6)
        FROM Lookup l
        WHERE l.Type = 'Sausage'
    UNION ALL
    SELECT 'Halibut', 'Fish', COALESCE(l.Number, 7)
        FROM Lookup l
        WHERE l.Type = 'Fish'

Using a temporary table:

CREATE TEMPORARY TABLE tmpItems (
    Name VARCHAR(255),
    Type VARCHAR(255),
    Number INT
)

INSERT INTO tmpItems
    (Name, Type, Number)
    VALUES ('Pork', 'Sausage', 6)
INSERT INTO tmpItems
    (Name, Type, Number)
    VALUES ('Halibut', 'Fish', 7)

INSERT INTO Test.Items 
    (Name, Type, Number)
    SELECT t.Name, t.Type, COALESCE(l.Number, t.Number)
        FROM tmpItems t
            LEFT JOIN Lookup l
                ON t.Type = l.Type
0

精彩评论

暂无评论...
验证码 换一张
取 消