简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM