Roel
Roel

Reputation: 47

MySQL query for view slow performance

I have the following query used in a view:

select `a`.`device_id` AS `device_id`,
       `a`.`alias` AS `alias`,
       `a`.`freq` AS `freq`,
       `a`.`gateway` AS `gateway`,
       `a`.`device_lat` AS`device_lat`,
       `a`.`device_long` AS `device_long`,
       `a`.`device_disabled` AS `device_disabled`,
       count(`b`.`msg_id`) AS `total_messages`,
       avg(`b`.`rssi`) AS `avg_rssi`,
       max(`b`.`db_timestamp`) AS `last_active`,
       (now() <= (max(`b`.`db_timestamp`) + interval 3 hour)) AS `device_status`
from `demo`.`lora_device` `a` 
left join `demo`.`lora_message` `b` on `a`.`device_id` = `b`.`eui` 
group by `a`.`device_id`

This query takes about 4 seconds to load, info about the tabes:

lora_message : 25k rows about 20 columns

lora_device : 520 rows about 10 columns

Usually I would say this would not be a problem for mysql, but for some reason it is going very slow.

Upvotes: 1

Views: 604

Answers (1)

Radim Bača
Radim Bača

Reputation: 10701

Try to add indexes

 create index ix_loramessage_rssi on lora_message(eui, rssi)
 create index ix_loramessage_db_timestamp on lora_message(eui, db_timestamp)

and use

 count(`b`.`rssi`) AS `total_messages`,

instead of

 count(`b`.`msg_id`) AS `total_messages`,

since it should return the same result in your query

Upvotes: 1

Related Questions