select from two tables each with different join - mysql

Trying to run this query will not return any error but I guess there is still something wrong in it. After four minutes running it keeps elaborating:
SELECT DISTINCT azioni_row.id_az, sofferenze.Descrizione, COUNT(crediti.stato = 'aperta') as aperti, COUNT(crediti.stato = 'chiusa') as chiusi
FROM (`azioni_row`, sofferenze)
JOIN crediti ON azioni_row.id_cred=crediti.id_cre
JOIN azioni_head as ah1 ON azioni_row.id_az=ah1.id_az
JOIN azioni_head as ah2 ON ah2.id_soff = sofferenze.id_soff
GROUP BY id_az
ORDER BY `azioni_row`.`id_az` ASC
If I remove sofferenze.Descrizione from the select list and sofferenze from the FROM list it runs in a few seconds:
SELECT DISTINCT azioni_row.id_az, COUNT(crediti.stato = 'aperta') as aperti, COUNT(crediti.stato = 'chiusa') as chiusi
FROM azioni_row
JOIN crediti ON azioni_row.id_cred=crediti.id_cre
JOIN azioni_head as ah1 ON azioni_row.id_az=ah1.id_az
GROUP BY id_az
ORDER BY `azioni_row`.`id_az` ASC
I would like to show the Descrizione field but the link for it is in the head table, not in the row one. The relationship between head and row is a one to many. I store in head all the info that is not necessary to repeat for each row and the link with Descrizione is one of these fields.
EDIT:
this is the explain:
this is the create for azioni_head:
CREATE TABLE `azioni_head` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tipo` varchar(2) NOT NULL,
`id_az` varchar(11) NOT NULL,
`id_soff` varchar(11) NOT NULL,
`id_soff_gar` varchar(11) DEFAULT NULL,
`date_from` date NOT NULL,
`date_to` date NOT NULL,
`close_why` int(11) NOT NULL,
`RGE` varchar(30) NOT NULL,
`procedente` varchar(2) NOT NULL,
`curatore` varchar(11) NOT NULL,
`legale` varchar(11) NOT NULL,
`tribunale` varchar(11) NOT NULL,
`riparto` varchar(2) NOT NULL DEFAULT '0',
`perc_worst` decimal(13,10) NOT NULL,
`perc_best` decimal(13,10) NOT NULL,
`perc_poster` decimal(13,10) NOT NULL,
`attivo_storico` decimal(65,2) NOT NULL,
`passivo_storico` decimal(65,2) NOT NULL,
`attivo_storico_comm` decimal(65,2) NOT NULL,
`passivo_storico_comm` decimal(65,2) NOT NULL,
`acconti` decimal(65,2) NOT NULL,
`acconti_comm` decimal(65,2) NOT NULL,
`numero_comm` int(11) NOT NULL,
`legali_worst` decimal(65,2) NOT NULL,
`legali_best` decimal(65,2) NOT NULL,
`manuale` tinyint(1) NOT NULL DEFAULT '0',
`created_by` int(11) NOT NULL,
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1449 DEFAULT CHARSET=utf8 COMMENT='tabella testata azioni'
this for azioni_row:
CREATE TABLE `azioni_row` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_az` varchar(11) NOT NULL,
`id_cred` varchar(11) NOT NULL,
`chiesto` decimal(65,2) NOT NULL,
`ammesso` decimal(65,2) NOT NULL,
`data_ammesso` date NOT NULL,
`rango_ammesso` tinytext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4479 DEFAULT CHARSET=utf8
and this for sofferenze
CREATE TABLE `sofferenze` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_soff` varchar(11) NOT NULL,
`Descrizione` tinytext NOT NULL,
`gruppo` int(11) NOT NULL,
`cointestazione` int(11) NOT NULL,
`port_man` tinytext NOT NULL,
`head_port_man` tinytext NOT NULL,
`note` longtext NOT NULL,
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `id_3` (`id`),
KEY `id_2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1716 DEFAULT CHARSET=utf8

Please provide proper CREATE statements as well as the output of:
EXPLAIN
SELECT a.id_az
, s.Descrizione
, COUNT(c.stato = 'aperta') aperti
, COUNT(c.stato = 'chiusa') chiusi
FROM azioni_row a
JOIN sofferenze s
CROSS
JOIN crediti c
ON c.id_cre = a.id_cred
JOIN azioni_head ah1
ON ah1.id_az = a.id_az
JOIN azioni_head ah2
ON ah2.id_soff = s.id_soff
GROUP
BY a.id_az
, s.Descrizione
ORDER
BY a.id_az ASC
Edit: You seem to have lots of indexes on the same column. Drop all indexes except the PRIMARY KEYs, and create the following indexes:
sofferenze: id_soff
azioni_row: try a composite index on (id_az,id_cred)
azioni_head: an index on id_soff and an index on id_az
Crediti is missing so I can't comment on that one.

Related

Subquery returning null

Got this confusing issue where I need to get data from several tables and join them into one result.
This query was working fine:
select simcard.*,customer.name as cuname,mi,ma,co, tot from simcard, customer,
(SELECT s.sim_id AS ssim_id, min(datetime) AS mi, max(datetime) AS ma, FLOOR(sum(t.WEIGHT) / 1000) AS tot,
(SELECT count(datetime)
FROM transactions t
WHERE (t.SIM_ID = ssim_id) AND t.ROWTYPE LIKE '$D' GROUP BY t.sim_id) as co
FROM simcard s, transactions t
WHERE (s.sim_id = t.sim_id) AND t.ROWTYPE LIKE '$Z'
AND ( s.customer_id =1 ) GROUP BY s.sim_id) as T
WHERE (sim_id = ssim_id) AND (simcard.customer_id = customer.id) GROUP BY simcard.SIM_ID
But when I add a new customer and new simcard to that customer, it will return empty. I'm guessing this is because there is not transaction with that sim_id in the transaction able.
I've tried to left join but I'm just getting errors.
I've narrowed it down to the first subquery, removing the second one did not result in an non-empty result, but because both subqueries uses the transaction table I'm guessing that both will need some left join.
Structure:
DROP TABLE IF EXISTS `customer`;
CREATE TABLE IF NOT EXISTS `customer` (
`ID` int(10) NOT NULL AUTO_INCREMENT,
`NAME` varchar(40) DEFAULT NULL,
`API` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`ID`),
KEY `CUSTOMER_ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Tabellstruktur `simcard`
--
DROP TABLE IF EXISTS `simcard`;
CREATE TABLE IF NOT EXISTS `simcard` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`SIM_ID` char(20) DEFAULT NULL,
`CUSTOMER_ID` char(10) DEFAULT NULL,
`SCALES_ID` char(10) DEFAULT NULL,
`NAME` varchar(40) DEFAULT NULL,
`ACTIVE` char(1) DEFAULT 'N',
`EMAIL` varchar(255) DEFAULT NULL,
`TARGET_WEIGHT` varchar(255) DEFAULT NULL,
`LICENSE` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`ID`),
KEY `SIM_ID` (`SIM_ID`),
KEY `CUSTOMER_ID` (`CUSTOMER_ID`),
KEY `SCALES_ID` (`SCALES_ID`),
KEY `SIM_ID_2` (`SIM_ID`,`CUSTOMER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Tabellstruktur `transactions`
--
DROP TABLE IF EXISTS `transactions`;
CREATE TABLE IF NOT EXISTS `transactions` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`SCALES_ID` char(10) DEFAULT NULL,
`SIM_ID` char(20) DEFAULT NULL,
`ROWTYPE` char(2) DEFAULT NULL,
`DATETIME` datetime DEFAULT NULL,
`TRANSACTIONTIME` int(11) DEFAULT NULL,
`NAME` varchar(255) DEFAULT NULL,
`TRANSACTIONNUMBER` int(11) DEFAULT NULL,
`DATA0` varchar(255) DEFAULT NULL,
`DATA1` varchar(255) DEFAULT NULL,
`DATA2` varchar(255) DEFAULT NULL,
`DATA3` varchar(255) DEFAULT NULL,
`DATA4` varchar(255) DEFAULT NULL,
`DATA5` varchar(255) DEFAULT NULL,
`DATA6` varchar(255) DEFAULT NULL,
`DATA7` varchar(255) DEFAULT NULL,
`DATA8` varchar(255) DEFAULT NULL,
`MEMORY` varchar(255) DEFAULT NULL,
`MATERIAL` varchar(255) DEFAULT NULL,
`DENSITY` int(11) DEFAULT NULL,
`VEHICLETYPE` char(1) DEFAULT NULL,
`TOOLNAME` varchar(255) DEFAULT NULL,
`WEIGHT` int(11) DEFAULT NULL,
`TRANSACTIONID` int(11) DEFAULT NULL,
`group_id` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`ID`),
KEY `SIM_ID` (`SIM_ID`),
KEY `TRANSACTIONID` (`TRANSACTIONID`),
KEY `SCALES_ID` (`SCALES_ID`),
KEY `SIM_ID_2` (`SIM_ID`,`TRANSACTIONID`),
KEY `idx_transactions_ROWTYPE` (`ROWTYPE`),
KEY `idx_transactions_DATETIME` (`DATETIME`),
KEY `idx_transactions_DATA0` (`DATA0`),
KEY `idx_transactions_DATA1` (`DATA1`),
KEY `idx_transactions_DATA2` (`DATA2`),
KEY `idx_transactions_DATA3` (`DATA3`),
KEY `idx_transactions_DATA4` (`DATA4`),
KEY `idx_transactions_DATA5` (`DATA5`),
KEY `idx_transactions_DATA6` (`DATA6`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
COMMIT;
Expected result:
ID SIM_ID CUSTOMER_ID SCALES_ID NAME ACTIVE EMAIL TARGET_WEIGHT LICENSE cuname mi ma co tot
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
8 10100421287868 1 61 M-61M Y NULL NULL 0 testcustomer 2018-04-26 00:00:00 2018-08-08 00:00:00 14908 529446

MYSQL: Left Join is very slow

I'm using MySQl for my database and I have three tables where I want to join them using left join but the performance are very slow.
Below are the tables:
CREATE TABLE IF NOT EXISTS `register_doctor` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`doc_title` int(11) NOT NULL,
`first_name` varchar(35) NOT NULL,
`last_name` varchar(35) DEFAULT NULL,
`gender` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`province_id` int(11) NOT NULL,
`specialty_id` int(11) NOT NULL,
`status` int(11) NOT NULL COMMENT '0 = Pending; 1 = Verified, 2 = Not Reg Yet, 3 = Pending Approval',
`str_number` char(6) DEFAULT NULL,
`editted_by` int(11) DEFAULT NULL,
`editted_date` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `city_id` (`city_id`),
KEY `specialty_id` (`specialty_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10267 ;
CREATE TABLE IF NOT EXISTS `ref_doctor_practice_place` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`doctor_id` int(11) NOT NULL,
`practice_place_id` int(11) NOT NULL,
`is_primary` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `doctor_id_2` (`doctor_id`,`practice_place_id`),
KEY `doctor_id` (`doctor_id`),
KEY `practice_place_id` (`practice_place_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=23677 ;
CREATE TABLE IF NOT EXISTS `practice_place` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(75) NOT NULL,
`statement` text,
`address` varchar(200) NOT NULL,
`phone` varchar(15) NOT NULL,
`fax` varchar(15) NOT NULL,
`email` varchar(50) NOT NULL,
`village_id` varchar(50) NOT NULL,
`sub_district_id` varchar(50) NOT NULL,
`province_id` varchar(50) NOT NULL,
`zipcode` varchar(10) NOT NULL,
`website` varchar(50) NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`type` int(11) NOT NULL,
`managed_by` int(11) DEFAULT '0',
`doctor_group_id` int(11) NOT NULL,
`category` varchar(50) NOT NULL,
`photo_file` char(36) NOT NULL,
`is_branch` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`editted_by` int(11) NOT NULL,
`editted_date` bigint(20) NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `village_id` (`village_id`),
KEY `doctor_group_id` (`doctor_group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=24182 ;
My query is like this:
SELECT SQL_CALC_FOUND_ROWS RD.id as rd_id
, RD.first_name
, RD.last_name
, RD.gender
, RD.str_number
, GROUP_CONCAT(DISTINCT PP.type SEPARATOR '|') as pp_type
FROM register_doctor RD
LEFT
JOIN ref_doctor_practice_place RDPP
ON RDPP.doctor_id = RD.id
LEFT
JOIN practice_place PP
ON PP.id = RDPP.practice_place_id
GROUP
BY RD.id
ORDER
BY RD.id DESC
LIMIT 0,25
Can anyone help me about this? Many thanks.
As requested by Strawberry, here I put the result of using EXPLAIN:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE RD index PRIMARY,city_id PRIMARY 4 NULL 15 NULL
1 SIMPLE RDPP ref doctor_id doctor_id 4 k6064619_lokadok.RD.id 1 NULL
1 SIMPLE PP eq_ref PRIMARY,id PRIMARY 4 k6064619_lokadok.RDPP.practice_place_id 1 NULL
I'm sorry guys. I should have posted the real query. The left join acutally is like this:
LEFT JOIN ref_doctor_practice_place RDPP ON **ABS(RDPP.doctor_id) = RD.id**
I thought the ABS didn't really matter so I erase it to make it more straight forward. But actually this is the culprit.
Nothing wrong with my query. So case close. Thanks for any attempt to help me. Appreciate it.

Perf of select mysql query is really bad

I'm not sure why this query is taking 4 minutes to complete:
SELECT
su.sid,u.uid,u.display_name,u.locale
FROM user u
LEFT JOIN subscription_user su ON su.uid = u.uid
ORDER BY u.display_name DESC
LIMIT 0,25;
Well, I know it's due to the order, remove it and it's very fast. If I change to using INNER JOIN instead it's fast but the issue is not all users may be in the subscription_user table.
CREATE TABLE `user` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(100) DEFAULT NULL,
`user_type` varchar(10) NOT NULL DEFAULT 'user',
`display_name` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`locale` varchar(8) DEFAULT 'en',
`last_login` datetime DEFAULT NULL,
`auth_type` varchar(10) DEFAULT NULL,
`auth_data` varchar(500) DEFAULT NULL,
`inactive` tinyint(4) NOT NULL DEFAULT '0',
`receive_email` tinyint(4) NOT NULL DEFAULT '1',
`stateid` int(10) DEFAULT NULL,
`owner_group_id` int(11) DEFAULT NULL,
`signature` varchar(500) DEFAULT NULL,
`raw_signature` varchar(500) DEFAULT NULL,
`round_robin` smallint(5) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`uid`),
UNIQUE KEY `email` (`email`),
KEY `stateid` (`stateid`) USING BTREE,
KEY `user_type` (`user_type`) USING BTREE,
KEY `name` (`display_name`)
) ENGINE=InnoDB AUTO_INCREMENT=28343 DEFAULT CHARSET=latin1;
CREATE TABLE `subscription_user` (
`sid` varchar(50) NOT NULL,
`uid` int(11) NOT NULL,
`deleted` tinyint(4) NOT NULL DEFAULT '0',
`forum_user` varchar(50) NOT NULL,
PRIMARY KEY (`sid`,`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
When you have an SQL query, the index can only really help you if the first column in the index is part of the query.
Your query joins su.uid = u.uid and the optimizer will not be able to use that to reference the first column in the subscription primary key index.
You should either reverse the order of the columns in the primary key, or alternatively, you should add a foreign key index, or an independent index on the uid

MySQL SELECT query with joins takes too long

I have the following SELECT query with table joins and it taking about a minute to return 6 records:
SELECT * FROM specimen, topography_index, morphology, specimen_image_lookup, image
WHERE
SUBSTRING(specimen.topography_index, 2, 2) = topography_index.topography_index_code
AND
morphology.morphology_code = specimen.snop_code
AND
specimen_image_lookup.specimen_fk = specimen.specimen_pk
AND
image.image_pk = specimen_image_lookup.image_fk
AND
specimen.topography_index, 2, 2) IN('".implode("','",$system)."')
Any ideas what I should here?
Table structures are:
CREATE TABLE `specimen` (
`specimen_pk` int(4) NOT NULL AUTO_INCREMENT,
`number` varchar(20) NOT NULL,
`unit_number` varchar(10) NOT NULL,
`topography_index` varchar(5) NOT NULL DEFAULT '',
`snop_axis` char(1) NOT NULL,
`snop_code` varchar(4) NOT NULL,
`example` int(2) NOT NULL,
`gender` char(1) NOT NULL,
`age` varchar(3) NOT NULL DEFAULT 'NA',
`clinical_history` text NOT NULL,
`specimen` text NOT NULL,
`macroscopic` text NOT NULL,
`microscopic` text NOT NULL,
`conclusion` text NOT NULL,
`comment` text NOT NULL,
`room` char(1) NOT NULL,
`position` varchar(8) NOT NULL,
`created` datetime NOT NULL,
`created_by` int(3) NOT NULL,
`updated` datetime NOT NULL,
`updated_by` int(3) NOT NULL,
PRIMARY KEY (`specimen_pk`),
FULLTEXT KEY `clinical_history` (`clinical_history`),
FULLTEXT KEY `specimen` (`specimen`),
FULLTEXT KEY `macroscopic` (`macroscopic`),
FULLTEXT KEY `microscopic` (`microscopic`),
FULLTEXT KEY `conclusion` (`conclusion`),
FULLTEXT KEY `comment` (`comment`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=500 ;
CREATE TABLE `topography_index` (
`topography_index_pk` int(3) NOT NULL AUTO_INCREMENT,
`topography_index_code` varchar(2) DEFAULT NULL,
`topography_index_nomen` text,
PRIMARY KEY (`topography_index_pk`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=138 ;
CREATE TABLE `specimen_image_lookup` (
`specimen_image_lookup_pk` int(8) NOT NULL AUTO_INCREMENT,
`specimen_fk` int(4) NOT NULL,
`image_fk` int(4) NOT NULL,
PRIMARY KEY (`specimen_image_lookup_pk`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=141 ;
CREATE TABLE `morphology` (
`morphology_pk` int(6) NOT NULL AUTO_INCREMENT,
`morphology_code` varchar(4) NOT NULL,
`morphology_nomen` varchar(120) NOT NULL,
PRIMARY KEY (`morphology_pk`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2295 ;
CREATE TABLE `image` (
`image_pk` int(4) NOT NULL AUTO_INCREMENT,
`image_title` varchar(80) NOT NULL,
`image_description` text NOT NULL,
`image_thumbnail` varchar(100) NOT NULL,
`image_small` varchar(100) NOT NULL,
`image_large` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`created_by` int(3) NOT NULL,
`updated` datetime NOT NULL,
`updated_by` int(3) NOT NULL,
PRIMARY KEY (`image_pk`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=138 ;
By performing a substring on specimen.topography_index, you're asking the database to perform that calculation on every row in the specimen table before finding if the value exists in topography_index. One way to address this is to store the actual integer value that will match with topography_index, rather than a string with that value embedded.

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;