MySQL如果存在插入id,则插入到两个表中

时间:2015-11-21 14:43:30

标签: mysql sql

我已经制作了以下SQL语句,它不起作用,也无法弄清楚如何创建一个正常的语句。这是我想要做的。

  1. 检查玩家表中是否存在值
  2. 如果值存在,我想将ignore插入名册表
  3. 如果该值不存在,我想将其插入到播放器表中并将其插入到名册表中
  4. 这是我的

    Intersects(a.span,b.span)

    感谢任何帮助!

    我尝试了另一种没有运气的尝试

    IF EXISTS (SELECT id AS plyrId FROM players WHERE email = @(:e) LIMIT 1)
    BEGIN
        INSERT IGNORE INTO roster
            (date, teamId, playerId)
        VALUES
            ( (:d), (:t), plyrId )
    END
    ELSE
    BEGIN
        INSERT INTO players 
            (status, date, first_name, last_name, email) 
        VALUES 
            ( (:s), (:d), (:f), (:l), (:e) )
    
        INSERT IGNORE INTO roster
            (date, teamId, playerId)
        VALUES
            ( (:d), (:t), LAST_INSERT_ID() )  //LAST_INSERT_ID() -> I want it to be pulled from the last id inserted from the players table - not sure how to accomplish this
    END
    

2 个答案:

答案 0 :(得分:0)

您必须在插入

之前在事件上使用触发器
CREATE TRIGGER test_trigger BEFORE INSERT ON `players table` FOR EACH ROW SET
-- checking value exist or not, for each case write corresponding insert or inserts

答案 1 :(得分:0)

这部分查询非常可疑:

IF EXISTS (SELECT id AS plyrId FROM players WHERE email = @(:e) LIMIT 1)
BEGIN
    INSERT IGNORE INTO roster
        (date, teamId, playerId)
    VALUES
        ( (:d), (:t), plyrId )
----------------------^
END

除非你有一个名为plyrId的变量,否则这将失败。在子查询中分配别名不会在外部查询中定义变量。

您可以将其替换为:

INSERT IGNORE INTO roster(date, teamId, playerId)
    SELECT (:d), (:t), id 
    FROM players
    WHERE email = @(:e)
    LIMIT 1;

或者,您可以将if更改为:

IF EXISTS (SELECT plyrdId := id FROM players WHERE email = @(:e) LIMIT 1)