插入数据问题 父子表是同一个表 本帖最后由 pickup_liu 于 2010-05-19 16:15:32 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 insert into type(id, rootid, name) values(1, 1, '运动');像这类父子表,不建议id使用identity字段。 问题1:这样虽然能插入成功 但下次插入时 先要浏览一下该表数据 确定此次插入rootid所用的值insert into type(rootid,name)values(last_insert_id(),'阅读')虽然解决了问题1,但插入的成功后并不是此次插入的主键值 既然你有parentid, 你再用autoincrement作parentid,就无法自己来控制了。建议parentid就用普通的int 字段,你自己去控制如何生成它。 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) MySQL 中无法解决这个应用问题。MySQL的外键不允许为NULL。所以在插入第一个节点的时候比较麻烦。一般这种应用下是不在使用数据库的外键约束。 (插入该记录时 其中另一个字段值就等于这次插入记录的主键id值)真的没有解决的方法了吗?insert into type set rootid=本次插入的主键id,name='book'; mysql帮忙优化一条sql语句,模仿Oracle函数 row_number() over()函数实现分组后自增长,请大神帮忙。 mysql远程的问题 求助连接池问题。 为什么连不上mysql 怎么通过外部表的查询结果进行排序 请教关于mysql直接拷贝的数据库导出的问题,提示1045,情况有点特殊 感觉比较难的一个sql语句,大家帮我想想 mysql中如何删除含有空字段的记录? 再次请教各位大侠!怎样将myisam类型的表转换成InnoDB 表类型 php&mysql高手请进!!! 求助:C API调MySQL长时间运行会导致连接失败! mysql time_zone 可以有哪些取值?
像这类父子表,不建议id使用identity字段。
insert into type(rootid,name)values(last_insert_id(),'阅读')虽然解决了问题1,但插入的成功后并不是此次插入的主键值
-> 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)
所以在插入第一个节点的时候比较麻烦。一般这种应用下是不在使用数据库的外键约束。
insert into type set rootid=本次插入的主键id,name='book';