本帖最后由 pickup_liu 于 2010-05-19 16:15:32 编辑

解决方案 »

  1.   

     insert into type(id, rootid, name) values(1, 1, '运动');
    像这类父子表,不建议id使用identity字段。
      

  2.   

    问题1:这样虽然能插入成功 但下次插入时 先要浏览一下该表数据 确定此次插入rootid所用的值
    insert into type(rootid,name)values(last_insert_id(),'阅读')虽然解决了问题1,但插入的成功后并不是此次插入的主键值
      

  3.   

    既然你有parentid, 你再用autoincrement作parentid,就无法自己来控制了。建议parentid就用普通的int 字段,你自己去控制如何生成它。
      

  4.   

    mysql> create table type1(
        ->   id int(4) not null,
        ->   rootid int(4) not null default 0,
        ->   name varchar(20) not null default '',
        ->   primary key(id),
        ->   index(rootid),
        ->   CONSTRAINT fk_rootid foreign key(rootid) references type1(id) on delete cascade
        -> );
    Query OK, 0 rows affected (0.03 sec)mysql> set @a=0;
    Query OK, 0 rows affected (0.00 sec)mysql> set @a=@a+1;insert into type1 values(@a, @a, 'abc');
    Query OK, 0 rows affected (0.04 sec)Query OK, 1 row affected (0.01 sec)mysql> set @a=@a+1;insert into type1 values(@a, 1, 'abcd');
    Query OK, 0 rows affected (0.00 sec)Query OK, 1 row affected (0.01 sec)mysql> set @a=@a+1;insert into type1 values(@a, 2, 'abcde');
    Query OK, 0 rows affected (0.00 sec)Query OK, 1 row affected (0.01 sec)mysql> select * from type1;
    +----+--------+-------+
    | id | rootid | name  |
    +----+--------+-------+
    |  1 |      1 | abc   | 
    |  2 |      1 | abcd  | 
    |  3 |      2 | abcde | 
    +----+--------+-------+
    3 rows in set (0.00 sec)
      

  5.   

    MySQL 中无法解决这个应用问题。MySQL的外键不允许为NULL。
    所以在插入第一个节点的时候比较麻烦。一般这种应用下是不在使用数据库的外键约束。
      

  6.   

    (插入该记录时 其中另一个字段值就等于这次插入记录的主键id值)真的没有解决的方法了吗?
    insert into type set rootid=本次插入的主键id,name='book';