MySQL SELECT或INSERT如果行尚不存在

时间:2015-02-03 13:59:51

标签: mysql sql database insert

我有3个简单的表:
球员:
CREATE TABLE IF NOT EXISTS players (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(20), UNIQUE KEY (name));

竞技场:
CREATE TABLE IF NOT EXISTS arenas (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40), UNIQUE KEY (name));

和要点:
CREATE TABLE IF NOT EXISTS points (playerID INTEGER, arenaID INTEGER, points INTEGER, PRIMARY KEY (playerID, arenaID));

我想在points表中插入新行,并在需要时自动向玩家和竞技场插入行,目前我只是简单的INSERT:

INSERT INTO points (playerID, arenaID, points) 
VALUES 
(
    (SELECT players.id FROM players WHERE players.name LIKE ?),
    (SELECT arenas.id FROM arenas WHERE arenas.name LIKE ?),
    ?
) ON DUPLICATE KEY UPDATE points.points = LEAST(points.points, VALUES(points.points));

?将替换为值 热门编辑这个SQL,所以如果没有玩家(SELECT players.id FROM players WHERE players.name LIKE ?)那么它会将新玩家INSERT到这个表,这与竞技场相同。
喜欢:(我的伪代码)

INSERT INTO points (playerID, arenaID, points) 
VALUES 
(
    (SELECT players.id FROM players WHERE players.name LIKE "Mary" ON KEY NOT EXIST INSERT INTO players (name) VALUES ("Mary")),
    (SELECT arenas.id FROM arenas WHERE arenas.name LIKE "BigBoy" ON KEY NOT EXIST INSERT INTO arenas (name) VALUES ("BigBoy")),
    200
) ON DUPLICATE KEY UPDATE points.points = LEAST(points.points, VALUES(points.points));

仍然插入新的points行。

2 个答案:

答案 0 :(得分:1)

为什么不分三步执行,可以使用存储过程

IF NOT EXISTS arenas (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40), UNIQUE KEY (name))
begin
    INSERT INTO arenas (name) VALUES ("BigBoy")
end
IF NOT EXISTS players (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(20), UNIQUE KEY (name))
begin
    INSERT INTO players (name) VALUES ("Mary")
end

INSERT INTO points (playerID, arenaID, points) 
VALUES 
(
    (SELECT players.id FROM players WHERE players.name LIKE "Mary"),
    (SELECT arenas.id FROM arenas WHERE arenas.name LIKE "BigBoy"),
    200
) ON DUPLICATE KEY UPDATE points.points = LEAST(points.points, VALUES(points.points));

答案 1 :(得分:1)

您可以使用INSERT IGNORE声明。

INSERT IGNORE INTO players (name) VALUES (?);

INSERT IGNORE INTO arenas (name) VALUES (?);

INSERT INTO points (playerID, arenaID, points) 
VALUES 
(
    (SELECT players.id FROM players WHERE players.name LIKE ?),
    (SELECT arenas.id FROM arenas WHERE arenas.name LIKE ?),
    ?
) ON DUPLICATE KEY UPDATE points.points = LEAST(points.points, VALUES(points.points));