I have a log table like this that saves all logs for all of my table in my MySQL database:
+-------+-----------+-------------+-------------+-----------+--------+
| LogID | LogTypeID | LogDateTime | ReferenceID | TableName | UserID |
+-------+-----------+-------------+-------------+-----------+--------+
| 1 | 1 | 2012-10... | 1 | client | 1 |
| 2 | 1 | 2012-10... | 1 | plan | 1 |
| ... | ... | ... | ... | ... | ... |
+-------+-----------+-------------+-------------+-----------+--------+
The log table saves all the logs when I Insert, Update, or Delete to my tables in my database which is identified by my LogTypeID column. The ReferenceID column is the Primary Key of the table identified in my TableName column, all my Primay Keys has the same type of int(10) and it is same for the ReferenceID column.
I always use my log table for identifying when this data was inserted so I cannot clear the logs.
I have no problem on it at first, but now my queries are becoming slow when using the log table because of many data. I try to improve the performance of my database server and it become a little faster than before, but still it is slow. Most of my queries INNER JOIN to the log table.
I was thinking of adding a Foreign Key to my ReferenceID to all the tables that uses the log table because I think Keys may improve the performance of my queries, but I’m not sure if it is feasible.
Can I make my ReferenceID column a foreign key to all my tables?
My database server is MySQL Server 5.5.25, my tables are all InnoDB.
Please help, thanks in advance.
If I understand correctly and
ReferenceIDholds different tablePRIMARY KEYvalues, you will not be able to define it as aFOREIGN KEY, since aFOREIGN KEYconstraint is only able to reference a single table and cannot switch based on other column values.Instead, you can create an index on each of
ReferenceIDandTableName, or perhaps even a composite index across both of them:Or as a composite index across both columns, assuming you always need both to query against
log.