Conditional table reference I have a table tree:

+------+-------+
| id   | name  |
+------+-------+
| 0    | tree1 |
| 1    | tree2 |
| 2    | tree3 |
| 3    | tree4 |
+------+-------+


A table pen:

+------+------+
| id   | name |
+------+------+
| 0    | pen1 |
| 1    | pen2 |
| 2    | pen3 |
| 3    | pen4 |
+------+------+


And a third table task that "attaches" a task to either a tree or a pen:

+------+------+-------+
| type | id   | name  |
+------+------+-------+
| 0    | 1    | foo   |
| 0    | 2    | bar   |
| 1    | 1    | fee   |
| 1    | 2    | beer  |
+------+------+-------+


When type is 0, it means id references a tree. When type is 1, it references a pen (and so on with many different tables).

How can I do this and ensure referential integrity?
Creating a table task adding a refer id field for each referred table, in this way:


type : I prefer something as 'tree', 'pen'. Use an enum for this: ENUM('tree', 'pen');
tree_id : int (it can be NULL), that refers to tree table;
pen_id : int (it can be NULL), that refers to pen table;
name : varchar;


Some test data:

+------+---------+--------+-------+
| type | tree_id | pen_id | name  |
+------+---------+--------+-------+
| tree | 1       | NULL   | foo   |
| tree | 2       | NULL   | bar   |
| pen  | NULL    | 1      | fee   |
| pen  | NULL    | 2      | beer  |
+------+---------+--------+-------+