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.)

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改