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 ReferenceID holds different table PRIMARY KEY values, you will not be able to define it as a FOREIGN KEY, since a FOREIGN KEY constraint 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 ReferenceID and TableName, or perhaps even a composite index across both of them:
CREATE INDEX `idx_referenceid` ON `log` (`ReferenceID`);
CREATE INDEX `idx_tablename` ON `log` (`TableName`);
Or as a composite index across both columns, assuming you always need both to query against log.
CREATE INDEX `idx_referenceid_tablename` ON `log` (`ReferenceID`,`TableName`);
Related
I tried to create an index on MySQL using this query
CREATE TABLE test (id INT, age INT, INDEX(id,age));
DESCRIBE test; gives this:
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | YES | MUL | NULL | |
| age | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
When i tried to found why just the id was indexed i found 2 more things. That CREATE INDEX query requeires a name for the index and also that there is a USE INDEX () statement.
Now my questions:
Is the first query wrong or did I indexed both the id and the age like a pair and that's why just ID shows to be indexed?
Can I create indexes without providing a name, as I did in the first query (or when setting a column PRIMARY KEY)?
Should I add USE INDEX everytime I want to use the index? If yes, are there situations when the index is used by default (for example, when creating an index without a name, if possible)?
Your create table query with index - is ok, you can check it by running command
SHOW INDEX FROM test you'll see your index.
In general, it's good practice to create an index with own name (even you can omit it like in your query).
And USE INDEX - it's query performance optimization keyword which is just a suggestion which key mysql can use (you mush use it only if you clearly understand what are you doing, you must not use it for everyone query).
Use SHOW CREATE TABLE; it is more descriptive than DESCRIBE !
The DESCRIBE that you presented disagrees with the existence of INDEX(id,age).
Normally, id is the PRIMARY KEY of a table. You have broken with tradition; please explain what your intent is.
Do not use USE INDEX or FORCE INDEX -- it may help 'today', but is likely to hurt 'tomorrow'. Let the Optimizer decide which (if any) index to use.
We can't critique a schema without knowing what SELECTs you will be using against it.
Every table should have a PRIMARY KEY. Note: A PK is, by definition (in MySQL) both UNIQUE and INDEX.
There is almost no use for the name of an index. If you don't name an index, a name will be generated. A name is necessary when DROPping the index.
I have a badly designed database in hands. It has some tables with are related to each other by fields that were supposed to be foreign keys. For example, if they were to tables, each of them have a primary key, and the second contains the a column which was supposed to be a foreign key, but it is just a filed manually controlled to maintain the relationship.
My problem is finding a way to copy those tables to a second database, which have the same tables, with its own entries.
I tough about a select statement, excluding the primary key, and putting NULL in the first column(the primary key). By doing so, I could dump the records into a CVS and send it to the second DB, which would use automatic increment for the primary key. However, this would be a problem for the second table, as I would not know the new keys.
| Table A | | Table B |
| keyA | | keyB |
| fields | | keyA |
I'm sure this is simple stuff to many of you, so I hope you can help easily.
If I have a MySQL table on the "many" side of a "one to many" relationship - like this:
Create Table MyTable(
ThisTableId int auto_increment not null,
ForeignKey int not null,
Information text
)
Since this table would always be used via a join using ForeignKey, it would seem useful to make ForeignKey a clustered index so that foreign keys would always be sorted adjacently for the same source record. However, ForeignKey is not unique, so I gather that it is either not possible or bad practice to make this a clustered index? If I try and make a composite primary key using (ForeignKey, ThisTableId) to achieve both the useful clustering and uniqueness, then there is an error "There can only be one auto column and it must be defined as a key".
I think perhaps I am approaching this incorrectly, in which case, what would be the best way to index the above table for maximum speed?
InnoDB requires that if you have an auto-increment column, it must be the first column in a key.
So you can't define the primary key as (ForeignKey, ThisTableId) -- if ThisTableId is auto-increment.
You could do it if ThisTableId were just a regular column (not auto-increment), but then you would be responsible for assigning a value that is at least unique among other rows with the same value in ForeignKey.
One method I have seen used is to make the column BIGINT UNSIGNED, and use a BEFORE INSERT trigger to assign the column a value from the function UUID_SHORT().
#ypercube correctly points out another solution: The InnoDB rule is that the auto-increment column should be the first column of some key, and if you create a normal secondary key, that's sufficient. This allows you to create a table like the following:
CREATE TABLE `MyTable` (
`ForeignKey` int(11) NOT NULL,
`ThisTableId` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`ForeignKey`,`ThisTableId`),
KEY (`ThisTableId`)
) ENGINE=InnoDB;
And the auto-increment works as expected:
mysql> INSERT INTO MyTable (ForeignKey) VALUES (123), (234), (345), (456);
mysql> select * from MyTable;
+------------+-------------+
| ForeignKey | ThisTableId |
+------------+-------------+
| 123 | 1 |
| 234 | 2 |
| 345 | 3 |
| 456 | 4 |
+------------+-------------+
I have 3 tables: users, pages and users_pages
Users Table
+----+------+-----
| id | name | ...
+----+------+-----
Pages Table
+----+------+-----
| id | name | ...
+----+------+-----
users_pages table, which says, which user is admin of which page.
+---------+---------+
| user_id | page_id |
+---------+---------+
| 1 | 1 | // means, user 1 is admin of page 1
+---------+---------+
in users_pages table, combination of user_id and page_id is a compound key ( primary key )
Is it possible to define user_id and page_id as foreign key while they both together are primary key?
Yes, Absolutely. You havn't mentioned which relational database you are using, but this is common practice, and allowable in all relational databases i know of.
My attempt at an additional explanation:-
Primary and foreign keys are more like 'theoretical' things rather than hard physical things. When looking at the nuts and bolts, I find it useful to think of only indexes and contraints, not of 'keys' as such
Thinking this way a 'primary key' is actually a combination of two separate things :-
A unique contraint. This checks for and refuses any attempts to
create duplicates.
An index based on the field. This just makes
it much faster to retrieve the record if you use that field to look
it up (select * from table where pkey = 'x')
A 'foreign key' in practice is just a contraint, not much different from the unique key contraint. It checks the records exist in the other table, and refuses any attempts to create records with no corresponding entries in the referred to table.
There is no reason why you cant have multiple contraints on the same field (that it is both unique and exists in another table), and whatever indexes is on the table in no way prevents you from adding any contraint you like. Therefore there is no problem having the same field as part of a primary key and it also have a foreign key contraint.
I'm designing a plugin for a high traffic forum. What I am doing is listing related threads using a search API, which has a maximum of 800 searches per day
What I'm wanting to do is create a database to store the results, cache them for one day so it will be used instead of the API.
Would a table layout such as this be optimal:
Table:
+---------+-----------+------------+
| threadid | relatedids | dateentered |
+---------+-----------+------------+
| 129314 | 1124;2144 | 1234567890 |
| 124129 | 1251;1241 | 1234567890 |
| 185292 | 1151;5125 | 1234567890 |
+----------+-----------+-----------+
related urls being thread ID's too, separated by colons. I am not too much an expert in SQL so I do not know if setting index to threadID is a good idea, or what!
You clearly have a one-to-many relationship here, so you should use 2 tables instead of a separator, something like (MySQL syntax, assuming there is also a table named thread) :
create table search_thread (
thread_id int,
date_entered datetime,
PRIMARY KEY (thread_id)
FOREIGN KEY (thread_id) REFERENCES thread(thread_id));
create table search_results (
thread_id int,
result_id int,
PRIMARY KEY (thread_id, result_id),
FOREIGN KEY (thread_id) REFERENCES search_thread(thread_id),
FOREIGN KEY (thread_id) REFERENCES thread(thread_id).
FOREIGN KEY (result_id) REFERENCES thread(thread_id));
The benefit of this model is that it's open to extension, meaning you can add an attribute specific to the related threads. Also, you can perform some queries that are not possible with your approach, like finding how many threads are related to another (in both directions).