开发者

MySQL Join with Insert combined?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜