I’ve a problem with an enormous table in a database of an RoR application.
This is a part of my MySql database:
TABLE DEVICES:
create_table "devices", :force => true do |t|
t.string "mac"
end
TABLE EVENTS:
create_table "events", :force => true do |t|
t.integer "id"
t.integer "device_id"
t.string "data_type"
t.integer "element_id"
...
end
A device has_many events, so this table is very big.
the problem is when i want to find a record in this table by this query:
SELECT SQL_NO_CACHE
element_id,
created_at,
device_id,
multimedia_id
FROM events
WHERE device_id = N
AND data_type = 'S'
AND element_id = N
LIMIT N
the problem is:
No index was used here. In this case, that meant scanning 930447 rows..
In fact, the primary key in “id”.
What can i do?
I had to think about:
- change the primary key but RoR have no Composite Primary Key.
- divide the events table in many table, one for each device. How? What will the association become? (Table
has_many?) - can i link a table by a string? for example
"Events".where(...)?
can anyone help me?
Sorry for my English. bye.
Davide Lentini
Just because you should not use composite primary key doesn’t mean you can’t add a composite index (in a new migration):