doujiang1939 2015-09-20 14:51
浏览 26
已采纳

如何在插入表之前检查表中是否存在值?

I have a condition like this:

0 < $var < (SELECT col FROM tableA ORDER BY col DESC LIMIT 1)

Also I have an INSERT query like this:

INSERT INTO tableB (col) VALUES (?) ON DUPLICATE KEY UPDATE col = VALUE(col)

Now I want to know, how can I implement this in MySQL:

  • If the above condition was true, then insert new row, otherwise do nothing or give me an error?

    if (condition == true) then insert into table
    
  • 写回答

1条回答 默认 最新

  • dtxb75622 2015-09-20 15:35
    关注

    SELECT MAX(col) FROM tableA gives you the maximum value in column col from table tableA.

    I think what you're asking to do is:

    • If $val (a value from somewhere — presumably your PHP) is larger than 0 and smaller than the maximum value stored in the table tableA, then ensure that the value appears in the table tableB.

    If so, you might be able to use:

    INSERT INTO tableB(col)
        SELECT $val
          FROM dual
         WHERE $val > 0
           AND $val < (SELECT MAX(col) FROM tableA)
           AND NOT EXISTS(SELECT col FROM tableB WHERE col = $val)
    

    You now need to translate that into appropriate PHP.

    (See also MySQL conditional insert.)


    How can I add ON DUPLICATE KEY to my query?

    Also you can remove the AND NOT EXISTS(SELECT col FROM tableB WHERE col = $val) because col is unique and it prevents inserting duplicate.

    You don't need the ON DUPLICATE because the NOT EXISTS makes it irrelevant. And if you don't mind the error from an attempted duplicate insertion, you don't need any of this: you just do INSERT INTO tablaB(col) VALUES(?).

    AFAICS, the ON DUPLICATE clause does a no-op UPDATE; this avoids the need to do that. I suppose it wouldn't be a no-op if there are triggers on the table such that the 'last modified' (time, or user, or both) columns will be changed, or if the key of the table isn't the col column — these are pretty esoteric possibilities, though. You could have helped by showing an outline schema of the table indicating such features.

    If you really need the ON DUPLICATE clause, you can read the manual as well as I can and add it after the SELECT.

    INSERT INTO tableB(col)
        SELECT $val
          FROM dual
         WHERE $val > 0
           AND $val < (SELECT MAX(col) FROM tableA)
           AND NOT EXISTS(SELECT col FROM tableB WHERE col = $val)
        ON DUPLICATE KEY UPDATE col = VALUE(col)
    

    (And, of course, if you really don't want the NOT EXISTS clause, you can remove it.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题