2

I have a table like:

table: comments, with rows: id, author, content, replyto

I would like 'replyto' to reference 'id' in the same table, how would I do that?

Many thanks.

Tomas
  • 57,621
  • 49
  • 238
  • 373
fenerlitk
  • 5,414
  • 9
  • 29
  • 39

2 Answers2

3

Something like:

ALTER TABLE comments ADD CONSTRAINT `my_recursive_constraint` FOREIGN KEY (`reply_to`) REFERENCES `comments` (`id`) 
james_bond
  • 6,778
  • 3
  • 28
  • 34
0
alter table $table_name add foreign key references $table_name(id);

see this http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html (search for "self referential")

and this http://www.codeproject.com/KB/database/Trees_in_SQL_databases.aspx

bpgergo
  • 15,669
  • 5
  • 44
  • 68