i'm refactoring a db structure and have a little problem. This DB have various tables with same structure, like:

People -> People_contacts

Activities -> Activities_contacts

Now, i want to create only one Contact table, and use an ENUM() to distinguish from the nature of the parent (for search requirements and data reversibility)

the structure will be:

People -> Contacts[People]

Activities -> Contacts[Activities]

But now i need to put a Foreign-key, and based on the ENUM property distinguish from two different tables... How i can effort this? There are a way or is better maintain the old tables?

有帮助吗?

解决方案

why you are using view? if the People_contacts and Activities_contacts are exactly the same, you can try this:

create view `test` as select *,'People' as Type from `People_contacts` union select *,'Activities' from `Activities _contacts` union;

and then select what you want from the view:

select * from `test` where Type = 'People' and .....

and your query answer should be this

+----+------+   +--------+
| ID | Data |...| Type   |
+----+------+   +--------+
| 1  | foo  |...| People |
| 2  | foo  |...| People |
+----+------+   +--------+

其他提示

You cannot have a declared foreign key, pointing to one table or another depending on a field. You can do a few things, but none of then are really clean.

  1. You can have the integer field, and the enum, but do not declare the field as a foreign key. You will have to implement all the logic by yourself, and it will be harder to maintain, and harder to decouple database from programing.
  2. You can have 2 nullable foreign keys (people_id and activity_id), and forget the enum field. if one FK is null, the other will have the real relation. This is better since you declare the foreign keys as usual and the model is stronger
  3. If you prefer to keep your contact table clean, you can have a relation table where you put this dirty stuff. So in this table you store the contact_id, and the id of the activity or the person, as explained in whatever 1 or 2

But anyways, probably you are obfuscated and you dont need to have the foreign key in the contact table. I would bet you will always access first the people or the activities table, so you probably can change this tables, and add a contact_id foreign key. In the contact table you just need to add, if you dont have it already, de id primary key, and delete de ENUM field, and the foreign keys, since you dont really need them

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top