I’m trying to optimize a view in MySql. The view takes 0-5 records from a table and turns them into 1 record. The view works, but is slowing down as the # of records in the property_log table increases.
For example, data that looks like this:
mysql> select * from property_log where event_id = 1144882;
+----------+--------------+------------------------------+
| event_id | log_key | log_value |
+----------+--------------+------------------------------+
| 1144882 | userId | 1000 |
| 1144882 | licenseId | 3 |
| 1144882 | messageTypeId| 7 |
| 1144882 | message | Sample message |
| 1144882 | op | tracking |
+----------+--------------+------------------------------+
Gets turned into 1 record:
mysql> select * from view_logged_property where id = 1144882
+---------+--------+-----------+---------------+-------------------+
| ID | UserID | LicenseID | MessageTypeID | Message |
+---------+--------+-----------+---------------+-------------------+
| 1144882 | 1000 | 3 | 7 | Sample message |
+---------+--------+-----------+---------------+-------------------+
Edit: Important Note – Not all 5 records will be present all the time. For example, the data could also look like this:
mysql> select * from property_log where event_id = 1144882;
+----------+--------------+------------------------------+
| event_id | log_key | log_value |
+----------+--------------+------------------------------+
| 1144882 | userId | 1000 |
| 1144882 | messageTypeId| 7 |
| 1144882 | message | Sample message |
| 1144882 | op | tracking |
+----------+--------------+------------------------------+
The view I’m currently using to do this is the following:
DROP VIEW IF EXISTS view_logged_property;
CREATE VIEW view_logged_property as (
SELECT
p.event_id as ID,
(select log_value from property_log where log_key = "userId" and event_id = p.event_id) as UserID,
(select log_value from property_log where log_key = "licenseId" and event_id = p.event_id) as LicenseID,
(select log_value from property_log where log_key = "messageTypeId" and event_id = p.event_id) as MessageTypeID,
(select log_value from property_log where log_key = "message" and event_id = p.event_id) as Message
FROM
logging_event p
WHERE
p.event_id in (select event_id from property_log where log_key = "op" and log_value = "tracking")
);
What’s the best way to write this view so it’ll perform well even as the # of records in the “property_log” table increases?
I would use
joins in this case.Changed after comment
left joins should solve problem.Could you test it on your data?
Index on pair
event_id, log_keymight be required, sth like below:SQL Fiddle example