doumeitang572461 2013-08-04 06:41
浏览 109
已采纳

PHP-SQL自动添加增量数据

Hi I want to create a php-sql application for my case study where in I have these attributes:

Book ID, Book Name, Author, Editor, ISBN

the user will input the Book Name, Book ID, Author and Editor and automatically there will be an input for ISBN Number that is increments every time the user will input. Is that possible anyway? Well thanks for the help in advance.

  • 写回答

4条回答 默认 最新

  • donljt2606 2013-08-04 07:52
    关注

    It's unclear why you need this but you can achieve your goal with a BEFORE INSERT trigger and a separate table for sequencing

    Tables

    -- A sequencing table
    CREATE TABLE book_seq 
    (
      id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    );
    -- Set initial value
    ALTER TABLE book_seq AUTO_INCREMENT = 9000;
    
    CREATE TABLE books
    (
      book_id   INT,
      book_name VARCHAR(256), 
      author    VARCHAR(256),
      editor    VARCHAR(256),
      isbn      VARCHAR(12)
    );
    

    A trigger

    DELIMITER $$
    CREATE TRIGGER tg_book_seq
    BEFORE INSERT ON books
    FOR EACH ROW
    BEGIN
      INSERT INTO book_seq VALUES(NULL);
      SET NEW.isbn = CONCAT('8000-', LAST_INSERT_ID());
    END$$
    DELIMITER ;
    

    Now you can simply insert rows

    INSERT INTO books (book_id, book_name, author, editor) VALUES
    (1, 'Book1 Title', 'Author1', 'Editor1'),
    (2, 'Book2 Title', 'Author2', 'Editor1');
    

    Your pseudo ISBN number will be auto-generated

    | BOOK_ID |   BOOK_NAME |  AUTHOR |  EDITOR |      ISBN |
    ---------------------------------------------------------
    |       1 | Book1 Title | Author1 | Editor1 | 8000-9000 |
    |       2 | Book2 Title | Author2 | Editor1 | 8000-9001 |
    

    Here is SQLFiddle demo


    Another, much simpler, approach is to use INSERT ... SELECT syntax and calculate next pseudo ISBN number at the time of insert with the query like this

    INSERT INTO books (book_id, book_name, author, editor, isbn) 
    SELECT 1, 'Book1 Title', 'Author1', 'Editor1',
           CONCAT('8000-', COALESCE(SUBSTRING_INDEX(MAX(isbn), '-', -1), '8999') + 1) new_value
      FROM books
    

    Here is SQLFiddle demo

    Note: the major drawback of this approach is that it might fail under heavy load in concurrent environment when two or more concurrent users may have get the same MAX(isbn) value thus producing rows with the duplicate isbn number.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?