Very slow query when counting within combined tables - mysql

I'm having an issue with a particular SQL query running on one of my databases:
select
`map`,
`tier`,
(select count(*) from mapzones a where a.map = b.map
and `track` = 0 and `type` > 0) as `stages`,
(select count(*) from mapzones a where a.map = b.map
and `track` > 0 and `type` > 0) as `bonuses`
from
maptiers b
order by `map` asc;
The response takes ~28-30 seconds to execute, which is much too slow for what I need.
Strangely, when I execute a similar query on another database for a separate gamemode, it takes <100ms, usually <50ms:
select
`mapname`,
`tier`,
(select count(*) from ck_zones a where a.mapname = b.mapname
and `zonegroup` = 0 and (zonetype = 2
or zonetype = 3)) as `stages`,
(select count(*) from ck_zones a where a.mapname = b.mapname
and `zonegroup` > 0 and `zonetype` = 0) as `bonuses`
from
ck_maptier b
order by `mapname` asc;
Server Info
Server version: 8.0.29 - MySQL Community Server - GPL
Collation/Type
First Query's Database (BhopTimer)
Second Query's Database (SurfTimer)
(from Comment)
SELECT a.map, a.tier, b.stage_count
FROM maptiers a
INNER JOIN
(
SELECT DISTINCT map,
COUNT(CASE WHEN (type > 0 AND track = 0) THEN 1 END)
OVER (PARTITION BY map) AS `stage_count`
FROM mapzones
) AS b ON a.map = b.map
ORDER BY a.map;
Create Tables
CREATE TABLE `maptiers` (
`map` varchar(255) NOT NULL,
`tier` int NOT NULL DEFAULT '1',
PRIMARY KEY (`map`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE `mapzones` (
`id` int NOT NULL AUTO_INCREMENT,
`map` varchar(255) NOT NULL,
`type` int DEFAULT NULL,
`corner1_x` float DEFAULT NULL,
`corner1_y` float DEFAULT NULL,
`corner1_z` float DEFAULT NULL,
`corner2_x` float DEFAULT NULL,
`corner2_y` float DEFAULT NULL,
`corner2_z` float DEFAULT NULL,
`destination_x` float NOT NULL DEFAULT '0',
`destination_y` float NOT NULL DEFAULT '0',
`destination_z` float NOT NULL DEFAULT '0',
`track` int NOT NULL DEFAULT '0',
`flags` int DEFAULT '0',
`data` int DEFAULT '0',
`form` tinyint DEFAULT NULL,
`target` varchar(63) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14612 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE `ck_maptier` (
`mapname` varchar(54) NOT NULL,
`tier` int NOT NULL,
`maxvelocity` float NOT NULL DEFAULT '3500',
`announcerecord` int NOT NULL DEFAULT '0',
`gravityfix` int NOT NULL DEFAULT '1',
`ranked` int NOT NULL DEFAULT '1',
`stages` int DEFAULT NULL,
`bonuses` int DEFAULT NULL,
PRIMARY KEY (`mapname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE `ck_zones` (
`mapname` varchar(54) NOT NULL,
`zoneid` int NOT NULL DEFAULT '-1',
`zonetype` int DEFAULT '-1',
`zonetypeid` int DEFAULT '-1',
`pointa_x` float DEFAULT '-1',
`pointa_y` float DEFAULT '-1',
`pointa_z` float DEFAULT '-1',
`pointb_x` float DEFAULT '-1',
`pointb_y` float DEFAULT '-1',
`pointb_z` float DEFAULT '-1',
`vis` int DEFAULT '0',
`team` int DEFAULT '0',
`zonegroup` int NOT NULL DEFAULT '0',
`zonename` varchar(128) DEFAULT NULL,
`hookname` varchar(128) DEFAULT 'None',
`targetname` varchar(128) DEFAULT 'player',
`onejumplimit` int NOT NULL DEFAULT '1',
`prespeed` int NOT NULL DEFAULT '350',
PRIMARY KEY (`mapname`,`zoneid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Samples
First Query (BhopTimer)
maptiers.sql
mapzones.sql
Second Query (SurfTimer)
ck_maptier.sql
ck_zones.sql

See if they run faster when turned inside out:
SELECT b.map,
b.tier,
x.stages,
x.bonuses
FROM ( SELECT map,
SUM(track = 0 AND type = 0) AS stages,
SUM(track > 0 AND type > 0) AS bonuses
FROM mapzones
GROUP BY map ) AS x
JOIN maptiers AS b ON b.map = x.map
ORDER BY map ASC;
INDEXes:
mapzones: INDEX(map, track, type)
maptiers: INDEX(map, tier)
(For further discussion, please provide SHOW CREATE TABLE for each table. Also: EXPLAIN SELECT ...)

Related

Why is a query with one outer join taking so long?

I have the following query:
SELECT t.TOUR, t.ROUND, t.ID1, t.ID2
FROM belgarath.today_atp AS t
LEFT OUTER JOIN belgarath.match_ as m
ON m.tour_id = 0
AND t.TOUR = m.tours_ID_T
AND t.ROUND = m.rounds_ID_R
AND t.ID1 = m.today_players_ID1
AND t.ID2 = m.today_players_ID2
WHERE m.id_ IS NULL;
I'm looking to get the records from today_atp where they don't exist in match_.
I've given up on the query after 30 mins as this seems like it's taking too long for tables which have 700 rows (today_atp) and 1.4m rows (match_).
I tried just pulling one record via this query:
SELECT t.TOUR, t.ROUND, t.ID1, t.ID2
FROM belgarath.today_atp AS t
LEFT OUTER JOIN belgarath.match_ as m
ON m.tour_id = 0
AND t.TOUR = m.tours_ID_T
AND t.ROUND = m.rounds_ID_R
AND t.ID1 = m.today_players_ID1
AND t.ID2 = m.today_players_ID2
WHERE m.id_ IS NULL
AND t.TOUR = 16756
AND t.ROUND = 2
AND t.ID1 = 29591
AND t.ID2 = 37741;
This takes 30 seconds.
The specs for the two tables are as follows:
CREATE TABLE `match_` (
`id_` int DEFAULT NULL,
`date_time_scheduled` datetime DEFAULT NULL,
`date_time_actual` datetime DEFAULT NULL,
`tour_id` int NOT NULL,
`tournament_id` int DEFAULT NULL,
`tours_ID_T` int NOT NULL,
`rounds_ID_R` int NOT NULL,
`today_players_ID1` int DEFAULT NULL,
`today_players_ID2` int DEFAULT NULL,
`games_players_ID1` int DEFAULT NULL,
`games_players_ID2` int DEFAULT NULL,
`uncertainty_bin` int DEFAULT NULL,
`p1_win_pred_ogion` float DEFAULT NULL,
`p1_win_pred_rf_ogion` float DEFAULT NULL,
`p1_win_pred_ged` float DEFAULT NULL,
`p1_win_pred_rf_ged` float DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`winning_player` int DEFAULT NULL,
`completed_sets` int DEFAULT NULL,
`result_type_id` int DEFAULT NULL,
`p1_pinnacle_closing_odds` float DEFAULT NULL,
`p2_pinnacle_closing_odds` float DEFAULT NULL,
`p1_pinnacle_opening_odds` float DEFAULT NULL,
`p2_pinnacle_opening_odds` float DEFAULT NULL,
`post_match_data_retrieved` int DEFAULT NULL,
`updated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
KEY `ix_belgarath_match__tours_ID_T` (`tours_ID_T`),
KEY `ix_belgarath_match__today_players_ID1` (`today_players_ID1`),
KEY `ix_belgarath_match__games_players_ID1` (`games_players_ID1`),
KEY `ix_belgarath_match__tour_id` (`tour_id`),
KEY `ix_belgarath_match__rounds_ID_R` (`rounds_ID_R`),
KEY `ix_belgarath_match__today_players_ID2` (`today_players_ID2`),
KEY `ix_belgarath_match__games_players_ID2` (`games_players_ID2`),
KEY `ix_belgarath_match__uncertainty_bin` (`uncertainty_bin`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
And:
CREATE TABLE `today_atp` (
`TOUR` int NOT NULL DEFAULT '0',
`DATE_GAME` datetime DEFAULT NULL,
`ID1` int NOT NULL DEFAULT '0',
`ID2` int NOT NULL DEFAULT '0',
`ROUND` int NOT NULL DEFAULT '0',
`DRAW` int NOT NULL DEFAULT '0',
`RESULT` tinytext,
`COMPLETE` tinyint unsigned DEFAULT '0',
`live` char(70) DEFAULT NULL,
`TIME_GAME` datetime DEFAULT NULL,
`RESERVE_INT` smallint DEFAULT NULL,
`RESERVE_CHAR` char(64) DEFAULT NULL,
KEY `today_atp_TOUR` (`TOUR`) /*!80000 INVISIBLE */,
KEY `today_atp_ROUND` (`ROUND`) /*!80000 INVISIBLE */,
KEY `today_atp_ID1` (`ID1`) /*!80000 INVISIBLE */,
KEY `today_atp_ID2` (`ID2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Is there anything obvious that jumps out as to why it would be taking so long?
I have seen from other posts that CHARSET can be a problem but changing today_atp to utf8mb4 doesn't make a difference (I'm not sure how to set the COLLATE part via workbench).
(P.S. Some normalisation of the tables is definitely on my to do list!)

Not equals query is so slow

I have a query like that:
SELECT * , (
( 1584392725 ) - ( suprayts.time )
) AS timeDiff
FROM (
`suprayts`
)
WHERE `suprayts`.`is_deleted` = '0'
AND `suprayts`.`is_approved` =1
AND `suprayts`.`username` != 'rayben1'
AND `suprayts`.`time` >1584306325
ORDER BY `suprayts`.`is_boosted_by_user` DESC , `suprayts`.`id` ASC
LIMIT 10
This query runs very slow (avg 0.2 seconds), if i delete the following line:
AND `suprayts`.`username` != 'rayben1'
It runs 10x faster. (avg 0.02 secs) How can i speed up this query?
My indexes:
Explain:
My table:
CREATE TABLE IF NOT EXISTS `suprayts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(15) CHARACTER SET utf8 NOT NULL,
`question` varchar(70) COLLATE utf8mb4_unicode_ci NOT NULL,
`suprayt_photo` varchar(50) CHARACTER SET utf8 NOT NULL,
`time` int(11) NOT NULL,
`endTime` int(11) NOT NULL,
`datetext` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`like_count` int(10) unsigned NOT NULL DEFAULT '0',
`dislike_count` int(10) unsigned NOT NULL DEFAULT '0',
`is_approved` bit(1) NOT NULL DEFAULT b'0',
`is_deleted` enum('1','0') CHARACTER SET utf8 NOT NULL DEFAULT '0',
`is_end_notification_sent` bit(1) NOT NULL DEFAULT b'0',
`open_vote` enum('0','1') CHARACTER SET utf8 NOT NULL DEFAULT '1',
`boost` int(11) NOT NULL DEFAULT '0',
`is_boosted_by_user` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `username_3` (`username`,`suprayt_photo`),
KEY `id` (`id`,`time`,`is_approved`,`is_deleted`),
KEY `username` (`username`,`is_deleted`),
KEY `username_2` (`username`,`datetext`),
KEY `id_2` (`id`,`username`,`time`,`is_approved`,`is_deleted`),
KEY `username_4` (`username`,`time`,`is_approved`,`is_deleted`),
KEY `ix1` (`id`,`time`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=130789 ;
Depending on the SQL pre-compiler if one is being used, or the SQL itself, possible it is sensitive to the order of the query "where" clause not being in DB key order and it is not using the index and instead doing a sequential scan? Just to eliminate the possibility, try putting the WHERE items in the DB index key order.
USE NOT EXISTS
SELECT * , (
( 1584392725 ) - ( suprayts.time )
) AS timeDiff
FROM (
`suprayts`
)
WHERE `suprayts`.`is_deleted` = '0'
AND `suprayts`.`is_approved` =1
AND NOT EXISTS (
SELECT x.no FROM (SELECT 1 AS no) x WHERE `suprayts`.`username` = 'rayben1'
)
AND `suprayts`.`time` >1584306325
ORDER BY `suprayts`.`is_boosted_by_user` DESC , `suprayts`.`id` ASC
LIMIT 10

Advanced query running slowly

Whenever I am running this query, it takes about 25-30 seconds for it to run. As you can see, the most advanced thing here is to calculate two coalesces within subqueries.
SELECT
g.name,
g.id,
(
SELECT
COALESCE (
SUM(result2 / result1) * (
SUM(IF(result2 != 0, 1, 0)) * 0.1
),
0
) AS res
FROM
gump.war gwr
WHERE
started = 1
AND (UNIX_TIMESTAMP(time) + 7 * 24 * 60 * 60) > UNIX_TIMESTAMP()
AND gwr.guild1 = g.id
AND gwr.winner = g.id
) + (
SELECT
COALESCE (
SUM(result1 / result2) * (
SUM(IF(result1 != 0, 1, 0)) * 0.1
),
0
) AS res1
FROM
gumb.war gwr
WHERE
started = 1
AND (UNIX_TIMESTAMP(time) + 7 * 24 * 60 * 60) > UNIX_TIMESTAMP()
AND gwr.guild2 = g.id
AND gwr.winner = g.id
) AS avg
FROM
gumb.guild g
ORDER BY
avg DESC,
g.point DESC,
g.experience DESC LIMIT 10;
Table structures/schemas:
CREATE TABLE `guild` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(12) NOT NULL DEFAULT '',
`owner` int(10) unsigned NOT NULL DEFAULT '0',
`level` tinyint(2) DEFAULT NULL,
`experience` int(11) DEFAULT NULL,
`win` int(11) NOT NULL DEFAULT '0',
`draw` int(11) NOT NULL DEFAULT '0',
`loss` int(11) NOT NULL DEFAULT '0',
`point` int(11) NOT NULL DEFAULT '0',
`account` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
CREATE TABLE `war` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`guild1` int(10) unsigned NOT NULL DEFAULT '0',
`guild2` int(10) unsigned NOT NULL DEFAULT '0',
`time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`type` tinyint(2) unsigned NOT NULL DEFAULT '0',
`price` int(10) unsigned NOT NULL DEFAULT '0',
`score` int(10) unsigned NOT NULL DEFAULT '0',
`started` tinyint(1) NOT NULL DEFAULT '0',
`winner` int(11) NOT NULL DEFAULT '-1',
`result1` int(11) NOT NULL DEFAULT '0',
`result2` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
Indexes will definitely help, indexing fields used in JOIN criteria and in WHERE clauses carries the most impact.
Generic syntax example:
CREATE INDEX idx_col1col2 ON tbl_Test (Col1, Col2)
You don't likely want to just cram every field used into one index, and you likely shouldn't create an index for each field either.
There are many resources for helping you understand how to build your indexes, here are a couple items:
MySQL CREATE INDEX Syntax
MySQL Index Optimization

Mysql query with special characters?

I (newbie) have hard time to understand this query:
$result = mysql_query("
SELECT q.*, IF(v.id,1,0) AS voted
FROM quotes AS q
LEFT JOIN quotes_votes AS v
ON q.id = v.qid
AND v.ip =".$ip."
AND v.date_submit = '".$today."'
");
can anybody provide more info on what these short symbols like 'q.*' with the if statement and v.id,1,0. Any sources to read more about this?
Thank you very much.
this is how the tables looks like:
CREATE TABLE `quotes` (
`id` smallint(5) unsigned NOT NULL auto_increment,
`txt` varchar(255) collate utf8_unicode_ci NOT NULL default '',
`author` varchar(32) collate utf8_unicode_ci NOT NULL default '',
`bgc` varchar(32) collate utf8_unicode_ci NOT NULL default '',
`votes` mediumint(9) unsigned NOT NULL default '0',
`vsum` int(11) unsigned NOT NULL default '0',
`rating` double NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `rating` (`rating`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;
CREATE TABLE `quotes_votes` (
`id` mediumint(9) unsigned NOT NULL auto_increment,
`qid` smallint(6) unsigned NOT NULL default '0',
`ip` int(10) NOT NULL default '0',
`vote` tinyint(1) NOT NULL default '0',
`date_submit` date NOT NULL default '0000-00-00',
`dt_submit` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `qid` (`qid`,`ip`,`date_submit`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Regarding select q.*, it just means getting all fields from the table alias q, which happens to be table quotes. It is like select * but just for one table.
Regarding IF(v.id,1,0), that is really a MySQLism. The IF statement evaluates an expression given in the first argument and, if it is true, returns the second argument. Otherwise it returns the third argument. So you know that a 1 or a 0 will come out of the IF. You might now be wondering how can v.id be evaluated to return a logical value and the reason behind it is that MySQL treats booleans as if they were TINYINT(1) in which 0 is considered as false and non-zero values are considered as true.
So that would be rephrased into IF(v.id != 0, 1, 0) which might be easier to read. Given the fact that v.id can not be null then you could rewrite that this way IF(v.id = 0, 0, 1). Anyway, you could take a step further and just replace it with v.id != 0 :)

MySQL - Slow Multiple subquery & GROUP BY

When running the following query using GROUP BY it takes way too much time.
SELECT specialities.id AS ID_DEPARTMENT,
specialities.name AS ID_DEPARTMENT_NAME,
agenda.idagenda AS ID_SERVICE,
agenda.name AS ID_SERVICE_NAME,
supervisor.clients_waiting AS CWaiting,
IFNULL(supervisor.clients_resent_waiting_area, 0) AS CWaiting_Resent_Area,
supervisor.clients_attending AS CAttending,
supervisor.clients_attended AS CAttended,
(SELECT SUM(TIME_TO_SEC(TIMEDIFF(NOW(), time_waiting)) / CWaiting)
FROM supervisor_time_data
WHERE supervisor_time_data.id_service = supervisor.id_service) AS TME,
(SELECT SUM(TIME_TO_SEC(TIMEDIFF(NOW(), time_attending)) / CAttending)
FROM supervisor_time_data
WHERE supervisor_time_data.id_service = supervisor.id_service) AS TMA,
(SELECT TIME_TO_SEC(MAX(TIMEDIFF(NOW(), time_waiting)))
FROM supervisor_time_data
WHERE supervisor_time_data.id_service = supervisor.id_service) AS MTE,
(SELECT TIME_TO_SEC(MAX(TIMEDIFF(NOW(), time_attending)))
FROM supervisor_time_data
WHERE supervisor_time_data.id_service = supervisor.id_service) AS MTA,
supervisor.tme_accumulated AS TME_ACCUMULATED,
supervisor.tma_accumulated AS TMA_ACCUMULATED
FROM supervisor, supervisor_time_data, agenda, specialities
WHERE supervisor.id_service = agenda.id
AND supervisor_time_data.id_service = supervisor.id_service
AND agenda.idspeciality = specialities.id
AND supervisor.booked_or_sequential = 0
AND supervisor.id_service IN (1,2,3)
GROUP BY supervisor.id_service
ORDER BY agenda.name ASC;
It takes over 3 seconds, when commenting the GROUP BY line it takes 8 ms.
Any ideas on how I can optimise this query?
Thanks
EDIT:
CREATE TABLE `supervisor` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`id_department` int(6) DEFAULT NULL,
`id_service` int(9) DEFAULT NULL,
`clients_waiting` int(6) DEFAULT '0',
`clients_attending` int(6) DEFAULT '0',
`clients_attended` int(6) DEFAULT '0',
`tma_accumulated` int(9) DEFAULT '0',
`tme_accumulated` int(9) DEFAULT '0',
`clients_resent_waiting_area` int(6) DEFAULT NULL,
`booked_or_sequential` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_service` (`id_service`),
KEY `booked_or_sequential` (`booked_or_sequential`),
KEY `clients_waiting` (`clients_waiting`)
) ENGINE=MyISAM AUTO_INCREMENT=172 DEFAULT CHARSET=latin1;
.
CREATE TABLE `supervisor_time_data` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`id_ogs` int(32) DEFAULT NULL,
`booked_or_sequential` tinyint(1) DEFAULT NULL,
`time_waiting` datetime DEFAULT NULL,
`time_attending` datetime DEFAULT NULL,
`status` int(2) DEFAULT '0',
`id_service` int(6) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_service` (`id_service`),
KEY `time_waiting` (`time_waiting`),
KEY `time_attending` (`time_attending`),
KEY `booked_or_sequential` (`booked_or_sequential`)
) ENGINE=MyISAM AUTO_INCREMENT=2281 DEFAULT CHARSET=latin1;
.
CREATE TABLE `agenda` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`idagenda` varchar(255) DEFAULT NULL,
`iduser` int(3) DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
`agendatype` tinyint(4) DEFAULT NULL,
`idspeciality` int(6) DEFAULT NULL,
`denomination` varchar(255) DEFAULT NULL,
`ticket_count` int(3) DEFAULT NULL,
`waiting` int(3) DEFAULT NULL,
`ticket_start` int(3) DEFAULT NULL,
`ticket_end` int(3) DEFAULT NULL,
`ticket_letter` varchar(12) DEFAULT NULL,
`idcenter` int(9) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idagenda` (`idagenda`),
KEY `idspeciality` (`idspeciality`)
) ENGINE=MyISAM AUTO_INCREMENT=2228 DEFAULT CHARSET=latin1;
.
CREATE TABLE `specialities` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
`idwaitingarea` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=149 DEFAULT CHARSET=latin1;
Here is your queries with joins. Post your schema if this does not work.
SELECT
specialities.id AS ID_DEPARTMENT,
specialities.name AS ID_DEPARTMENT_NAME,
agenda.idagenda AS ID_SERVICE,
agenda.name AS ID_SERVICE_NAME,
supervisor.clients_waiting AS CWaiting,
IFNULL(supervisor.clients_resent_waiting_area, 0) AS CWaiting_Resent_Area,
supervisor.clients_attending AS CAttending,
supervisor.clients_attended AS CAttended,
SUM(TIME_TO_SEC(TIMEDIFF(NOW(), supervisor_time_data.time_waiting)) / supervisor.clients_waiting) AS TME,
SUM(TIME_TO_SEC(TIMEDIFF(NOW(), supervisor_time_data.time_attending)) / supervisor.clients_attending) AS TMA,
TIME_TO_SEC(MAX(TIMEDIFF(NOW(), supervisor_time_data.time_waiting))) AS MTE,
TIME_TO_SEC(MAX(TIMEDIFF(NOW(), supervisor_time_data.time_attending))) AS MTA,
supervisor.tme_accumulated AS TME_ACCUMULATED,
supervisor.tma_accumulated AS TMA_ACCUMULATED
FROM supervisor
LEFT JOIN supervisor_time_data
ON supervisor_time_data.id_service = supervisor.id_service
LEFT JOIN agenda
ON supervisor.id_service = agenda.id
LEFT JOIN specialities
ON agenda.idspeciality = specialities.id
WHERE supervisor.booked_or_sequential = 0
AND supervisor.id_service IN(1,2,3)
GROUP BY supervisor.id_service
ORDER BY agenda.name ASC;