There are two tables – posts and comments:
create table posts
(
id integer not null primary key auto_increment,
body text not null
);
create table comments
(
id integer not null primary key auto_increment,
body text not null,
post_id integer not null references posts(id)
);
Now I want to create one more table – reports(“bad post” flags) and I want it to store reports for both posts and comments.
create table reports
(
id integer not null primary key auto_increment,
obj_type tinyint not null, /* '1' for posts and '2' for comments */
obj_id integer not null,
body text not null
);
alter table reports add foreign key(obj_id) references posts(id) on delete cascade;
alter table reports add foreign key(obj_id) references comments(id) on delete cascade;
As you see there are two references in a single field (I differentiate them by obj_id), and the question is – Is it all right to do like this ?
If not what would be better solution?
Thanks in advance.
Intuitively that feels not the right way to do it. I think MySQL would be confused too; how would it validate that a constraint is being met; would it try
postsfirst, orcommentsfirst … maybe both?Personally I would choose to create two link tables:
comments <-> reportsposts <-> reportsThat way you disambiguate the
obj_idproperly.