期望:在mysql中
变通实现类似oracle中sequence的功能,自增,而且可以通过sql语句获得,
使用场景:将取得的值插入到两张表中,使这两张表的主键相同,问题就是如何取得这个值?希望高手指点,如何实现。

解决方案 »

  1.   

    http://topic.csdn.net/u/20090813/08/cc68f22c-f3f5-4037-9545-80ea489382cc.html?18813
    去看看吧!这里讨论得很详细。
      

  2.   

    mysql> create table t_csdn1111(id int auto_increment primary key, v char(10));
    Query OK, 0 rows affected (0.13 sec)mysql> insert into t_csdn1111(v) values ('A1');
    Query OK, 1 row affected (0.06 sec)mysql> select last_insert_id();
    +------------------+
    | last_insert_id() |
    +------------------+
    |                1 |
    +------------------+
    1 row in set (0.00 sec)
    mysql> select * from t_csdn1111 where id is null;
    +----+------+
    | id | v    |
    +----+------+
    |  1 | A1   |
    +----+------+
    1 row in set (0.00 sec)mysql> select auto_increment from information_schema.tables where table_schema='
    csdn' and table_name='t_csdn1111';
    +----------------+
    | auto_increment |
    +----------------+
    |              2 |
    +----------------+
    1 row in set (0.08 sec)mysql>
    mysql> insert into t_csdn1111(v) values ('A21'),('A22'),('A23');
    Query OK, 3 rows affected (0.06 sec)
    Records: 3  Duplicates: 0  Warnings: 0mysql> select last_insert_id();
    +------------------+
    | last_insert_id() |
    +------------------+
    |                2 |
    +------------------+
    1 row in set (0.00 sec)mysql> select * from t_csdn1111 where id is null;
    +----+------+
    | id | v    |
    +----+------+
    |  2 | A21  |
    +----+------+
    1 row in set (0.00 sec)mysql> select auto_increment from information_schema.tables where table_schema='
    csdn' and table_name='t_csdn1111';
    +----------------+
    | auto_increment |
    +----------------+
    |              5 |
    +----------------+
    1 row in set (0.00 sec)mysql>
      

  3.   

    获取当前会话的自增id:
    [code=SQL]select last_insert_id()注意:这个只适合单个insert的情况,不适合批量的情况,如 insrt into tb_name values(1),(2),(3)...若要获取全局的自增id:
    select auto_increment from information_schema.tables where table_schema='
    库名' and table_name='表名';[/code]
      

  4.   

    获取当前会话的自增id:
    select last_insert_id()注意:这个只适合单个insert的情况,不适合批量的情况,如 insrt into tb_name values(1),(2),(3)... 若要获取全局的自增id: 
    select auto_increment from information_schema.tables where table_schema=' 
    库名' and table_name='表名';