gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:48:59 25 4
gpt4 key购买 nike

我已经编写了以下 SQL 语句,但它不起作用,并且无法弄清楚如何创建一个正常运行的 SQL 语句。这就是我正在尝试做的事情。

  1. 检查玩家表中是否存在某个值
  2. 如果该值存在,我想将忽略插入名册表
  3. 如果该值不存在,我想将其插入到球员表中,并将其插入到名册表中

这是我所拥有的

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

感谢任何帮助!

我又尝试了一次,但还是没有成功

IF (SELECT COUNT(*) FROM players WHERE email = (:e) > 0)
INSERT IGNORE INTO roster
(date, teamId, playerId)
(:d), (:t), SELECT id FROM players WHERE email =(:e)
ELSE
BEGIN
.. // havent got to this part yet. it follows the same logic as the one before
END

最佳答案

您必须在事件插入之前使用触发器

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

关于MySQL如果存在则插入id否则插入到两个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com