MySQL Left Join on Max Value - mysql

In the table calendar_event there can be several calendar events (inspections). At present my query returns the oldest inspection (oldest if we rank them by the field ce.calendar_event_start), I want it to return the newest (latest) inspection.
I'm struggling with the approach to this. I've tried adding MAX around ce.calendar_event_start but that doesn't work. I'm assuming I have to change the LEFT JOIN but I can't figure out how I'd change it so that it's joining on the newest ce.calendar_event_start value.
UPDATE 1 - Thanks to #Vinit
Changed the LEFT JOIN as per the below but the query fails to execute;
LEFT JOIN calendar_event ce
on ce.calendar_event_tenancy = t.tenancy_id
AND ce.calendar_event_id = (SELECT calendar_event_id FROM
calendar_event ceInner
ceInner.calendar_event_tenancy = t.tenancy_id
AND ce.calendar_event_type='7'
AND ce.calendar_event_status!='3'
ORDER BY ceInner.calendar_event_start DESC)
UPDATE 2 - I worked on #Vinit answer to come up with the below that now works! Could this be improved any further?
Changed the LEFT JOIN as per the below but the query fails to execute;
LEFT JOIN calendar_event ce
on ce.calendar_event_tenancy = t.tenancy_id AND ce.calendar_event_id = (SELECT ceInner.calendar_event_id FROM
calendar_event ceInner
WHERE ceInner.calendar_event_tenancy = t.tenancy_id
AND ceInner.calendar_event_type='7'
AND ceInner.calendar_event_status!='3'
ORDER BY ceInner.calendar_event_start DESC
LIMIT 1)
UPDATE 3 - I've noticed the query takes a very long time to execute (approx 10 seconds). Is there a more efficient version of the same thing? Yes there is! See below;
LEFT JOIN calendar_event ce
on ce.calendar_event_tenancy = t.tenancy_id AND ce.calendar_event_start = (SELECT MAX(ceInner.calendar_event_start) FROM
calendar_event ceInner
WHERE ceInner.calendar_event_tenancy = t.tenancy_id
AND ceInner.calendar_event_type='7'
AND ceInner.calendar_event_status!='3'
AND ceInner.calendar_event_inspection_type!='2')
Query;
SELECT t.*, ce.*, IF(ce.calendar_event_start IS NOT NULL, ce.calendar_event_start, t.tenancy_start_date) AS LastInspection
FROM tenancy t
LEFT JOIN calendar_event ce
on ce.calendar_event_tenancy = t.tenancy_id AND ce.calendar_event_type='7' AND ce.calendar_event_status!='3'
ORDER BY LastInspection ASC
Tables & Sample Data;
-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jul 19, 2018 at 07:57 PM
-- Server version: 5.6.39
-- PHP Version: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `propsyst_main`
--
-- --------------------------------------------------------
--
-- Table structure for table `calendar_event`
--
CREATE TABLE `calendar_event` (
`calendar_event_id` int(11) NOT NULL,
`calendar_event_company_id` int(11) DEFAULT NULL,
`calendar_event_branch_id` int(11) DEFAULT NULL,
`calendar_event_subject` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`calendar_event_status` tinyint(4) DEFAULT NULL,
`calendar_event_start` datetime DEFAULT NULL,
`calendar_event_end` datetime DEFAULT NULL,
`calendar_event_location` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`calendar_event_type` tinyint(4) DEFAULT NULL,
`calendar_event_employee` int(11) DEFAULT NULL,
`calendar_event_description` text COLLATE utf8_bin,
`calendar_event_attendee_type` int(11) DEFAULT NULL,
`calendar_event_property` int(11) DEFAULT NULL,
`calendar_event_tenancy` int(11) DEFAULT NULL,
`calendar_event_applicant` int(11) DEFAULT NULL,
`calendar_event_valuation` int(11) DEFAULT NULL,
`calendar_event_meet_at` tinyint(4) DEFAULT NULL,
`calendar_event_date_created` datetime DEFAULT NULL,
`calendar_event_date_updated` datetime DEFAULT NULL,
`calendar_event_created_by` int(11) DEFAULT NULL,
`calendar_event_updated_by` int(11) DEFAULT NULL,
`calendar_event_feedback_position` text COLLATE utf8_bin,
`calendar_event_feedback_pros` text COLLATE utf8_bin,
`calendar_event_feedback_cons` text COLLATE utf8_bin,
`calendar_event_feedback_confidence_level` tinyint(4) DEFAULT NULL,
`calendar_event_feedback_public_comments` text COLLATE utf8_bin,
`calendar_event_feedback_private_comments` text COLLATE utf8_bin,
`calendar_event_confirmed_landlord_vendor` tinyint(4) DEFAULT NULL,
`calendar_event_confirmed_applicant` tinyint(4) DEFAULT NULL,
`calendar_event_notes` text COLLATE utf8_bin,
`calendar_event_private_notes` text COLLATE utf8_bin,
`calendar_event_branch` int(11) DEFAULT NULL,
`calendar_event_recurring_id` int(11) DEFAULT NULL,
`calendar_event_cancellation_reason` text COLLATE utf8_bin,
`calendar_event_surveyor_company_name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`calendar_event_surveyor_individual_name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`calendar_event_surveyor_phone_number` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`calendar_event_directory` int(11) DEFAULT NULL,
`calendar_event_inspection_type` tinyint(1) DEFAULT NULL,
`calendar_event_survey_type` tinyint(4) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `calendar_event`
--
INSERT INTO `calendar_event` (`calendar_event_id`, `calendar_event_company_id`, `calendar_event_branch_id`, `calendar_event_subject`, `calendar_event_status`, `calendar_event_start`, `calendar_event_end`, `calendar_event_location`, `calendar_event_type`, `calendar_event_employee`, `calendar_event_description`, `calendar_event_attendee_type`, `calendar_event_property`, `calendar_event_tenancy`, `calendar_event_applicant`, `calendar_event_valuation`, `calendar_event_meet_at`, `calendar_event_date_created`, `calendar_event_date_updated`, `calendar_event_created_by`, `calendar_event_updated_by`, `calendar_event_feedback_position`, `calendar_event_feedback_pros`, `calendar_event_feedback_cons`, `calendar_event_feedback_confidence_level`, `calendar_event_feedback_public_comments`, `calendar_event_feedback_private_comments`, `calendar_event_confirmed_landlord_vendor`, `calendar_event_confirmed_applicant`, `calendar_event_notes`, `calendar_event_private_notes`, `calendar_event_branch`, `calendar_event_recurring_id`, `calendar_event_cancellation_reason`, `calendar_event_surveyor_company_name`, `calendar_event_surveyor_individual_name`, `calendar_event_surveyor_phone_number`, `calendar_event_directory`, `calendar_event_inspection_type`, `calendar_event_survey_type`) VALUES
(5170, 100, 0, 'Property Inspection (Rent Arrears) with Ms xxx xxx at Apartment 1 1 Howard Drive, Aigburth, Liverpool, L19 XXX', 2, '2017-07-28 14:30:00', '2017-07-28 14:45:00', 'Apartment 1 1 Howard Drive, Aigburth, Liverpool, L19 XXX', 7, 1, 'Tenant(s): Ms xxx xxx (Mobile: 00000000000, Email: no.email#mailinator.com)\r\nMeeting with: Agent (Michael Le Brocq)\r\nInspection Type: Rent Arrears\r\nPublic Notes: Property Inspection due to late rent\r\nStatus: Confirmed\r\nOriginally Arranged: 28/07/17 11:45:19 by Jane Nicholson\r\nLast Updated: 19/07/18 16:00:59 by Michael Le Brocq', 1, 172, 82, 0, 0, 0, '2017-07-28 11:45:19', '2018-07-19 16:00:59', 33, 1, '', NULL, NULL, NULL, NULL, NULL, 0, 0, 'Property Inspection due to late rent', '', 1, NULL, '', '', '', '', 0, 2, 0),
(5931, 100, 0, 'Property Inspection (Rent Arrears) with Ms Susan XXX at Apartment 1 1 Howard Drive, Aigburth, Liverpool, L19 XXX', 2, '2017-10-30 12:00:00', '2017-10-30 12:30:00', 'Apartment 1 1 Howard Drive, Aigburth, Liverpool, L19 XXX', 7, 1, 'Tenant(s): Ms Susan XXX (Mobile: 00000000000, Email: no.email#mailinator.com)\r\nMeeting with: Agent (Michael Le Brocq)\r\nInspection Type: Rent Arrears\r\nPublic Notes: Tenant not paid the rent\r\nStatus: Confirmed\r\nOriginally Arranged: 25/10/17 13:11:32 by Jane Nicholson\r\nLast Updated: 19/07/18 16:02:50 by Michael Le Brocq', 1, 172, 82, 0, 0, 0, '2017-10-25 13:11:32', '2018-07-19 16:02:50', 33, 1, '', NULL, NULL, NULL, NULL, NULL, 0, 0, 'Tenant not paid the rent', '', 1, NULL, '', '', '', '', 0, 2, 0),
(8929, 100, 0, 'Property Inspection (Routine) with Ms Susan XXX at Apartment 1 1 Howard Drive, Aigburth, Liverpool, L19 XXX', 2, '2018-07-25 15:00:00', '2018-07-25 15:15:00', 'Apartment 1 1 Howard Drive, Aigburth, Liverpool, L19 XXX', 7, 36, 'Tenant(s): Ms Susan XXX (Mobile: 00000000000, Email: no.email#mailinator.com)\r\nMeeting with: Agent (Jan Borrows)\r\nInspection Type: Routine\r\nPublic Notes: Confirmed with Diane\r\nStatus: Confirmed\r\nOriginally Arranged: 17/07/18 15:37:54 by Jan Borrows\r\nLast Updated: 17/07/18 15:37:54 by Jan Borrows', 1, 172, 82, 0, 0, 0, '2018-07-17 15:37:54', '2018-07-17 15:37:54', 36, 36, '', NULL, NULL, NULL, NULL, NULL, 0, 0, 'Confirmed with Diane', '', 1, NULL, NULL, '', '', '', 0, 1, 0);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `calendar_event`
--
ALTER TABLE `calendar_event`
ADD PRIMARY KEY (`calendar_event_id`),
ADD UNIQUE KEY `calendar_event_id` (`calendar_event_id`),
ADD KEY `calendar_event_status` (`calendar_event_status`),
ADD KEY `calendar_event_start` (`calendar_event_start`),
ADD KEY `calendar_event_end` (`calendar_event_end`),
ADD KEY `calendar_event_property` (`calendar_event_property`),
ADD KEY `calendar_event_employee` (`calendar_event_employee`),
ADD KEY `calendar_event_type` (`calendar_event_type`),
ADD KEY `calendar_event_company_id` (`calendar_event_company_id`),
ADD KEY `calendar_event_branch_id` (`calendar_event_branch_id`),
ADD KEY `calendar_event_attendee_type` (`calendar_event_attendee_type`),
ADD KEY `calendar_event_applicant` (`calendar_event_applicant`),
ADD KEY `calendar_event_valuation` (`calendar_event_valuation`),
ADD KEY `calendar_event_meet_at` (`calendar_event_meet_at`),
ADD KEY `calendar_event_branch` (`calendar_event_branch`),
ADD KEY `calendar_event_recurring_id` (`calendar_event_recurring_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `calendar_event`
--
ALTER TABLE `calendar_event`
MODIFY `calendar_event_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8968;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
AND
-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jul 19, 2018 at 07:58 PM
-- Server version: 5.6.39
-- PHP Version: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `propsyst_main`
--
-- --------------------------------------------------------
--
-- Table structure for table `tenancy`
--
CREATE TABLE `tenancy` (
`tenancy_id` int(11) NOT NULL,
`tenancy_token` varchar(40) COLLATE utf8_bin DEFAULT NULL,
`tenancy_type` tinyint(4) DEFAULT NULL,
`tenancy_property` int(11) DEFAULT NULL,
`tenancy_furnished` int(11) DEFAULT NULL,
`tenancy_children` tinyint(4) DEFAULT NULL,
`tenancy_pets` tinyint(4) DEFAULT NULL,
`tenancy_smoking` tinyint(4) NOT NULL,
`tenancy_property_part` tinyint(4) DEFAULT NULL,
`tenancy_property_part_room` int(11) DEFAULT NULL,
`tenancy_property_part_description` text COLLATE utf8_bin,
`tenancy_shared_facilities` tinyint(4) DEFAULT NULL,
`tenancy_shared_facilities_description` text COLLATE utf8_bin,
`tenancy_agreement_date` date DEFAULT NULL,
`tenancy_start_date` date DEFAULT NULL,
`tenancy_fixed_term` smallint(6) DEFAULT NULL,
`tenancy_fixed_term_unit` tinyint(4) DEFAULT NULL,
`tenancy_fixed_term_end_date` date DEFAULT NULL,
`tenancy_rent_amount` decimal(8,2) DEFAULT NULL,
`tenancy_rent_frequency` int(11) DEFAULT NULL,
`tenancy_rent_payable` int(11) DEFAULT NULL,
`tenancy_rent_agreement` int(11) DEFAULT NULL,
`tenancy_rent_frequency_schedule` text CHARACTER SET utf8,
`tenancy_rent_payment_method` tinyint(4) DEFAULT NULL,
`tenancy_council_pay_rent` tinyint(4) DEFAULT NULL,
`tenancy_rent_vat_rate` tinyint(4) DEFAULT NULL,
`tenancy_service_charge_amount` decimal(8,2) DEFAULT NULL,
`tenancy_service_charge_frequency` int(11) DEFAULT NULL,
`tenancy_service_charge_payable` int(11) DEFAULT NULL,
`tenancy_service_charge_agreement` int(11) DEFAULT NULL,
`tenancy_service_charge_frequency_schedule` text COLLATE utf8_bin,
`tenancy_service_charge_payment_method` tinyint(4) DEFAULT NULL,
`tenancy_service_charge_vat_rate` tinyint(4) DEFAULT NULL,
`tenancy_insurance_amount` decimal(8,2) DEFAULT NULL,
`tenancy_insurance_frequency` int(11) DEFAULT NULL,
`tenancy_insurance_payable` int(11) DEFAULT NULL,
`tenancy_insurance_agreement` int(11) DEFAULT NULL,
`tenancy_insurance_frequency_schedule` text COLLATE utf8_bin,
`tenancy_insurance_payment_method` tinyint(4) DEFAULT NULL,
`tenancy_insurance_vat_rate` tinyint(4) DEFAULT NULL,
`tenancy_notes` text COLLATE utf8_bin,
`tenancy_agent_branch` int(11) DEFAULT NULL,
`tenancy_agent_employee` int(11) DEFAULT NULL,
`tenancy_letting_service` tinyint(4) DEFAULT NULL,
`tenancy_tenant_find_fee` decimal(10,2) DEFAULT NULL,
`tenancy_tenant_find_fee_type` tinyint(4) DEFAULT NULL,
`tenancy_management_fee` decimal(10,2) DEFAULT NULL,
`tenancy_management_fee_type` tinyint(4) DEFAULT NULL,
`tenancy_tenant_fee` decimal(6,2) DEFAULT NULL,
`tenancy_guarantor_fee` decimal(6,2) DEFAULT NULL,
`tenancy_reminder_letter_fee` decimal(6,2) DEFAULT NULL,
`tenancy_missed_payment_fee` decimal(6,2) DEFAULT NULL,
`tenancy_gas` tinyint(4) DEFAULT NULL,
`tenancy_electricity` tinyint(4) DEFAULT NULL,
`tenancy_water` tinyint(4) DEFAULT NULL,
`tenancy_oil` tinyint(4) DEFAULT NULL,
`tenancy_telephone` tinyint(4) DEFAULT NULL,
`tenancy_broadband` tinyint(4) DEFAULT NULL,
`tenancy_tv_licence` tinyint(4) DEFAULT NULL,
`tenancy_sat_cable_tv` tinyint(4) DEFAULT NULL,
`tenancy_council_tax` tinyint(4) DEFAULT NULL,
`tenancy_service_charge` tinyint(4) DEFAULT NULL,
`tenancy_ground_rent` tinyint(4) DEFAULT NULL,
`tenancy_deposit_required` tinyint(4) DEFAULT NULL,
`tenancy_deposit_amount` decimal(8,2) DEFAULT NULL,
`tenancy_deposit_protection_responsible` tinyint(4) DEFAULT NULL,
`tenancy_deposit_protection_scheme` tinyint(4) DEFAULT NULL,
`tenancy_status` tinyint(4) DEFAULT NULL,
`tenancy_renewal_status` tinyint(4) DEFAULT '4',
`tenancy_renewal_notes` text COLLATE utf8_bin,
`tenancy_move_out_date` date DEFAULT NULL,
`tenancy_move_out_reason` tinyint(4) DEFAULT NULL,
`tenancy_move_out_notes` text COLLATE utf8_bin,
`tenancy_tenant_find_with_management_fee` decimal(7,2) DEFAULT NULL,
`tenancy_tenant_find_with_management_fee_type` tinyint(4) DEFAULT NULL,
`tenancy_overdue_tc_reminders` tinyint(4) NOT NULL DEFAULT '1',
`tenancy_student` tinyint(4) DEFAULT NULL,
`tenancy_inspection_frequency` tinyint(4) DEFAULT NULL,
`tenancy_move_out_employee` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `tenancy`
--
INSERT INTO `tenancy` (`tenancy_id`, `tenancy_token`, `tenancy_type`, `tenancy_property`, `tenancy_furnished`, `tenancy_children`, `tenancy_pets`, `tenancy_smoking`, `tenancy_property_part`, `tenancy_property_part_room`, `tenancy_property_part_description`, `tenancy_shared_facilities`, `tenancy_shared_facilities_description`, `tenancy_agreement_date`, `tenancy_start_date`, `tenancy_fixed_term`, `tenancy_fixed_term_unit`, `tenancy_fixed_term_end_date`, `tenancy_rent_amount`, `tenancy_rent_frequency`, `tenancy_rent_payable`, `tenancy_rent_agreement`, `tenancy_rent_frequency_schedule`, `tenancy_rent_payment_method`, `tenancy_council_pay_rent`, `tenancy_rent_vat_rate`, `tenancy_service_charge_amount`, `tenancy_service_charge_frequency`, `tenancy_service_charge_payable`, `tenancy_service_charge_agreement`, `tenancy_service_charge_frequency_schedule`, `tenancy_service_charge_payment_method`, `tenancy_service_charge_vat_rate`, `tenancy_insurance_amount`, `tenancy_insurance_frequency`, `tenancy_insurance_payable`, `tenancy_insurance_agreement`, `tenancy_insurance_frequency_schedule`, `tenancy_insurance_payment_method`, `tenancy_insurance_vat_rate`, `tenancy_notes`, `tenancy_agent_branch`, `tenancy_agent_employee`, `tenancy_letting_service`, `tenancy_tenant_find_fee`, `tenancy_tenant_find_fee_type`, `tenancy_management_fee`, `tenancy_management_fee_type`, `tenancy_tenant_fee`, `tenancy_guarantor_fee`, `tenancy_reminder_letter_fee`, `tenancy_missed_payment_fee`, `tenancy_gas`, `tenancy_electricity`, `tenancy_water`, `tenancy_oil`, `tenancy_telephone`, `tenancy_broadband`, `tenancy_tv_licence`, `tenancy_sat_cable_tv`, `tenancy_council_tax`, `tenancy_service_charge`, `tenancy_ground_rent`, `tenancy_deposit_required`, `tenancy_deposit_amount`, `tenancy_deposit_protection_responsible`, `tenancy_deposit_protection_scheme`, `tenancy_status`, `tenancy_renewal_status`, `tenancy_renewal_notes`, `tenancy_move_out_date`, `tenancy_move_out_reason`, `tenancy_move_out_notes`, `tenancy_tenant_find_with_management_fee`, `tenancy_tenant_find_with_management_fee_type`, `tenancy_overdue_tc_reminders`, `tenancy_student`, `tenancy_inspection_frequency`, `tenancy_move_out_employee`) VALUES
(82, 'aJ9GCrxk9IEkBkLUqxsTuIdlbHnGNXTc4coq69AW', 1, 172, 2, 0, 0, 0, 1, 0, '', 0, '', '2014-08-21', '2014-08-21', 6, 2, '2015-02-20', '395.00', 3, 3, 1, '', 3, 0, 0, '0.00', 0, 0, 0, '', 0, 0, '0.00', 0, 0, 0, '', 0, 0, '', 1, 1, 3, '225.00', 1, '10.00', 2, '70.00', '50.00', '5.00', '15.00', 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 3, 1, '500.00', 1, 1, 1, 1, NULL, '0000-00-00', 0, '', '239.00', 1, 1, 0, 12, NULL);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tenancy`
--
ALTER TABLE `tenancy`
ADD PRIMARY KEY (`tenancy_id`),
ADD UNIQUE KEY `tenancy_token` (`tenancy_token`),
ADD KEY `tenancy_id` (`tenancy_id`),
ADD KEY `tenancy_property` (`tenancy_property`),
ADD KEY `tenancy_status` (`tenancy_status`),
ADD KEY `tenancy_letting_service` (`tenancy_letting_service`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tenancy`
--
ALTER TABLE `tenancy`
MODIFY `tenancy_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=526;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;

The order by on date column suppose to be descending to get latest inspection date
ORDER BY LastInspection DESC
EDIT
You may try this query -
SELECT t.*,
ce.*,
IF(
ce.calendar_event_start IS NOT NULL,
ce.calendar_event_start,
t.tenancy_start_date
) AS LastInspection
FROM tenancy t
LEFT JOIN calendar_event ce
on ce.calendar_event_tenancy = t.tenancy_id
AND ce.calendar_event_start = (select max(ceInner.calendar_event_start) from -- get the recent event id
calendar_event ceInner
ceInner.calendar_event_tenancy = t.tenancy_id
AND ceInner.calendar_event_type='7'
AND ceInner.calendar_event_status!='3'
)
ORDER BY LastInspection DESC

Related

MySQL - Why query does not sum same type of data if I use more left join?

My schema and sample data set:
CREATE TABLE `bsbi_hedge_fund` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`fund_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`abn_number` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
`parent_company_id` int(11) DEFAULT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`contact_no` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_one` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_two` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`city_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`state_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`zip_code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`country_tbl_id` int(11) DEFAULT NULL,
`status` varchar(10) COLLATE utf8_unicode_ci DEFAULT 'active',
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`modified_by` int(11) DEFAULT NULL,
`modified_date` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_hedge_fund`
--
INSERT INTO `bsbi_hedge_fund` (`id`, `fund_name`, `abn_number`, `parent_company_id`, `email`, `contact_no`, `address_one`, `address_two`, `city_name`, `state_name`, `zip_code`, `country_tbl_id`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
(1, 'iCAP Hedge Funds', '53616271062', 1, 'icaptrading#gmail.com', '0425175887', '68 Roy Marika Street', '', 'Bonner', 'ACT', '2914', 12, 'active', 1, '2020-02-20 07:02:51', NULL, NULL);
CREATE TABLE `bsbi_company` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`company_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`abn_number` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
`acn_number` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`contact_no` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_one` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`address_two` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`city_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`state_name` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
`zip_code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`country_tbl_id` int(11) DEFAULT NULL,
`status` varchar(10) COLLATE utf8_unicode_ci DEFAULT 'active',
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`modified_by` int(11) DEFAULT NULL,
`modified_date` datetime DEFAULT NULL,
`allocated_money` float(17,5) DEFAULT '0.00000',
`hedge_fund_allocation` float(17,5) NOT NULL,
`investment_class_allocation` float(17,5) NOT NULL,
`hedge_fund_money` float(10,3) DEFAULT '0.000',
`inv_class_money` float(10,3) DEFAULT '0.000'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_company`
--
INSERT INTO `bsbi_company` (`id`, `company_name`, `abn_number`, `acn_number`, `email`, `contact_no`, `address_one`, `address_two`, `city_name`, `state_name`, `zip_code`, `country_tbl_id`, `status`, `created_by`, `created_date`, `modified_by`, `modified_date`, `allocated_money`, `hedge_fund_allocation`, `investment_class_allocation`, `hedge_fund_money`, `inv_class_money`) VALUES
(1, 'Investment and Capital Growth for Australian Professional ( ', '53616271062', '2123', 'abc#gmail.com', '2343', '68 Roy Marika Street', '', 'Bonner', 'ACT', '2914', 12, 'active', 1, '2020-02-20 07:01:26', 1, '2020-03-07 12:13:53', 22847.00000, 0.00000, 0.00000, 20000.000, 19000.000);
CREATE TABLE `bsbi_hedge_fund_journal` (
`id` int(11) NOT NULL,
`company_id` int(11) DEFAULT NULL,
`hedge_fund_id` int(11) DEFAULT NULL,
`amount` float(10,3) DEFAULT NULL,
`tran_type` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
`modified_by` int(11) DEFAULT NULL,
`modified_date` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_hedge_fund_journal`
--
INSERT INTO `bsbi_hedge_fund_journal` (`id`, `company_id`, `hedge_fund_id`, `amount`, `tran_type`, `created_by`, `created_date`, `modified_by`, `modified_date`) VALUES
(1, 1, 1, 20000.000, 'credit', 1, '2020-03-07 11:45:40', NULL, NULL);
CREATE TABLE `bsbi_investment_allocation_class_journal` (
`id` int(11) NOT NULL,
`hedge_fund_id` int(11) DEFAULT NULL,
`investment_class_id` int(11) DEFAULT NULL,
`amount` float(10,3) DEFAULT NULL,
`tran_type` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_by` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `bsbi_investment_allocation_class_journal`
--
INSERT INTO `bsbi_investment_allocation_class_journal` (`id`, `hedge_fund_id`, `investment_class_id`, `amount`, `tran_type`, `created_by`, `created_date`) VALUES
(1, 1, 1, 18000.000, 'credit', 1, '2020-03-07 11:46:09'),
(2, 1, 1, 2000.000, 'credit', 1, '2020-03-07 12:12:02'),
(3, 1, 1, 1000.000, 'debit', 1, '2020-03-07 12:13:53');
...and fiddle of same ( http://sqlfiddle.com/#!9/9cd46d/2 ):
I have written the following query to fetch some data from the database:
SELECT
hf.*, com.company_name company_name, com.id com_id,
IFNULL( SUM( hfc.amount ), 0 ) hedge_credit, IFNULL( SUM( hfd.amount ), 0 ) hedge_debit,
IFNULL( SUM( cjc.amount ), 0 ) class_credit, IFNULL( SUM( cjd.amount ), 0 ) class_debit
FROM bsbi_hedge_fund hf
INNER JOIN bsbi_company com ON hf.parent_company_id = com.id
LEFT JOIN bsbi_hedge_fund_journal hfc ON (hfc.hedge_fund_id = hf.id AND hfc.tran_type='credit')
LEFT JOIN bsbi_hedge_fund_journal hfd ON ( hfd.hedge_fund_id = hf.id AND hfd.tran_type = 'debit' )
LEFT JOIN bsbi_investment_allocation_class_journal cjc ON (cjc.hedge_fund_id = hf.id AND cjc.tran_type = 'credit' )
LEFT JOIN bsbi_investment_allocation_class_journal cjd ON (cjd.hedge_fund_id = hf.id AND cjd.tran_type = 'debit' )
ORDER BY hf.id ASC
Here is the output of this query:
The problem I face is: hedge_credit value is 20000 but it shows 40000! similarly class_debit is 1000 but it shows 2000
After doing some R&D what I found is: bsbi_investment_allocation_class_journal table has two entry having tran_type = credit but for some unknown reason the following line of my query fetch two rows, rather sum the values (and I fear the same thing will happen to other left join if they also have more than one record of the same type!)
LEFT JOIN bsbi_investment_allocation_class_journal cjc ON (cjc.hedge_fund_id = hf.id AND cjc.tran_type = 'credit' )
If I add Group By clause to above query then I got:
Notice that class_credit has two different values that should sum up but does not sum for an unknown reason!!
Can anyone tell me what is actually wrong in my query that raises this issue?
- Thanks
Joins generate all possible combinations of rows that meet join criteria. Because you're using only hfc.hedge_fund_id = hf.id to join tables, you are duplicating rows. If there were three transactions in total, each would be tripled..
You'll need to select more data from the tables containing transactions to keep the rows unique: timestamps or transaction ids. I would usually select the unique rows that I want first, then left join the non-unique data (name, country, etc) to each row.
I got the solution from this: https://dba.stackexchange.com/questions/154586/sum-over-distinct-rows-with-multiple-joins
If someone faces the exact type of problem then they can check this solution: https://dba.stackexchange.com/questions/154586/sum-over-distinct-rows-with-multiple-joins

Mysql truncates the data

I can't upload data to mysql with csv upload.
I got this error now:
It says duplicate entry for '7'. but it is not 7 actually. it is 907 in the csv file I'm trying to upload. Mysql takes only 7 of 907 for some reason. How can i solve this problem? please. thanks.
-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 04, 2018 at 11:27 AM
-- Server version: 5.7.14
-- PHP Version: 5.6.25
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `mdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `ttb`
--
CREATE TABLE `ttb` (
`Week` int(11) NOT NULL,
`Date` date DEFAULT NULL,
`Sside` varchar(45) DEFAULT NULL,
`Schange` varchar(45) DEFAULT NULL,
`SRep` tinyint(4) DEFAULT NULL,
`SRepC` varchar(45) DEFAULT NULL,
`Opp` varchar(45) DEFAULT NULL,
`RuRpt` varchar(45) DEFAULT NULL,
`RaRpt` varchar(45) DEFAULT NULL,
`DuRpt` varchar(45) DEFAULT NULL,
`DaRpt` varchar(45) DEFAULT NULL,
`Dist1` varchar(15) DEFAULT NULL,
`Dist2` varchar(15) DEFAULT NULL,
`Dist3` varchar(15) DEFAULT NULL,
`Dist4` varchar(15) DEFAULT NULL,
`Dist5` varchar(15) DEFAULT NULL,
`Distin` varchar(15) DEFAULT NULL,
`Sint` varchar(15) DEFAULT NULL,
`Svar` varchar(15) DEFAULT NULL,
`Sdev` varchar(15) DEFAULT NULL,
`Smean` varchar(15) DEFAULT NULL,
`Smedian` varchar(15) DEFAULT NULL,
`Rerng` varchar(15) DEFAULT NULL,
`Bmedian` varchar(45) DEFAULT NULL,
`Opp1` varchar(45) DEFAULT NULL,
`Opp2` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and this is the beginning of CSV file that I want to upload:
906,24/10/2018,14,B,,7,,,,,x,4,,,2,3,4,1,2,1,1,1,0.3,,3,1
905,17/10/2018,5,A,,5,,,R1,S1,2x,,3,,2,3,1,4,1,2,1,1,,3,3,2

How can I do this MySQL Statements all in one?

I have a table with stocks and its prices. Moreover, I have all Rates in this table. Now I would like to get all MArketCAP in USD (= column MarketCap * FXRATE) for all stocks. The original MarketCAP column is in local currency. So I have to multiply by the latest rates.
To get the latetest rates I did following:
Table example:
DROP TABLE IF EXISTS `aktien`;
CREATE TABLE `aktien` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dummyfield` varchar(255) DEFAULT NULL,
`Company` varchar(255) DEFAULT NULL,
`Stock_Short` varchar(50) DEFAULT NULL,
`country` varchar(10) DEFAULT 'US',
`LastPrice` decimal(17,3) DEFAULT NULL,
`PrevClose` decimal(17,3) DEFAULT NULL,
`PercChange` varchar(50) DEFAULT NULL,
`DayLow` decimal(17,3) DEFAULT NULL,
`DayHigh` decimal(17,3) DEFAULT NULL,
`Dividend` decimal(17,3) DEFAULT '0.000',
`ExDATE` datetime DEFAULT NULL,
`ImportDATE` datetime DEFAULT NULL,
`TradeDate` date DEFAULT NULL,
`refTradeDate` datetime DEFAULT NULL,
`timed` time DEFAULT NULL,
`Open` decimal(17,3) DEFAULT '0.000',
`AfterHrsChange` varchar(200) DEFAULT NULL,
`Volume` bigint(20) DEFAULT '0',
`AskSize` int(17) DEFAULT '0',
`BidSize` int(17) DEFAULT '0',
`AvgDayVol` bigint(20) DEFAULT '0',
`50DMA` decimal(17,3) DEFAULT '0.000',
`200DMA` decimal(17,3) DEFAULT '0.000',
`52WeekHigh` decimal(17,3) DEFAULT '0.000',
`52WeekLow` decimal(17,3) DEFAULT '0.000',
`52WeekRange` varchar(200) DEFAULT NULL,
`MarketCap` varchar(200) DEFAULT NULL,
`EPS` decimal(17,3) DEFAULT '0.000',
`BV` decimal(17,3) DEFAULT '0.000',
`EBITDA` varchar(200) DEFAULT NULL,
`P2S` decimal(17,3) DEFAULT '0.000',
`P2B` decimal(17,3) DEFAULT '0.000',
`PE` decimal(17,3) DEFAULT '0.000',
`Revenue` varchar(200) DEFAULT NULL,
`Mean10LastPrice` decimal(17,3) DEFAULT '0.000',
`Mean20LastPrice` decimal(17,3) DEFAULT '0.000',
`Mean50LastPrice` decimal(17,3) DEFAULT '0.000',
`Mean100LastPrice` decimal(17,3) DEFAULT '0.000',
`Mean200LastPrice` decimal(17,3) DEFAULT '0.000',
`NewHigh` int(1) DEFAULT '0',
`NewLow` int(1) DEFAULT '0',
`stocktype` varchar(50) DEFAULT 'stock',
`NormLastPrice` decimal(17,3) DEFAULT NULL,
`trendcode` int(1) DEFAULT '0',
`Todayflag` int(1) DEFAULT '0',
`KGVC` decimal(17,3) DEFAULT NULL,
`KGVN` decimal(17,3) DEFAULT NULL,
`ShortRatio` decimal(17,3) DEFAULT NULL,
`EPSC` decimal(17,3) DEFAULT NULL,
`EPSN` decimal(17,3) DEFAULT NULL,
`Target1Y` decimal(17,3) DEFAULT NULL,
`AdjClose` decimal(17,3) DEFAULT NULL,
`DMANote` varchar(60) DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `Stock_Short` (`Stock_Short`,`TradeDate`)
) ENGINE=InnoDB AUTO_INCREMENT=1594308 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = #saved_cs_client */;
--
-- Dumping data for table `aktien_stack`
--
LOCK TABLES `aktien` WRITE;
/*!40000 ALTER TABLE `aktien_stack` DISABLE KEYS */;
INSERT INTO `aktien` VALUES (1592307,NULL,'LUFTHANSA AG VNA
`O.N','LHA.DE','DE',25.110,24.290,'0.033758733',24.150,25.340,0.800,
'2018-05-09 00:00:00','2018-05-11 20:01:06',
'2018-05-11',NULL,NULL,24.270,NULL,4681038,1900800,948200,3320935,
25.694,27.756,31.260,16.095,NULL,'11862591488',0.000,0.000,
'5404000256',0.333,0.000,4.990,'35650998272',
24.739,25.517,26.056,27.511,26.004,0,0,'stock',
NULL,0,0,0.333,NULL,NULL,NULL,NULL,NULL,NULL,''),
(1592660,NULL,'EUR/USD','EURUSD=X','US',1.194,1.192,'0.0020306304',
1.190,1.197,NULL,NULL,'2018-05-11 23:00:03',
'2018-05-11',NULL,NULL,1.192,NULL,0,0,0,0,1.223,
1.209,1.256,1.086,NULL,NULL,0.000,0.000,NULL,NULL,
0.000,NULL,NULL,0.000,0.000,0.000,0.000,0.000,0,0,
'cur',NULL,0,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'')
/*!40000 ALTER TABLE `aktien_stack` ENABLE KEYS */;
UNLOCK TABLES;
How can I do the multiplication of all MarketCap by the FXRATE of all stocks (consider that LocalCurrencyCountry = country) in one statement?
I have done this way: ( I think it might be done with a temp table, right?)
drop table if exists rr;
create TEMPORARY TABLE rr
SELECT s.Stock_Short,
s.country,
rate.country as LocalCurrencyCountry,
s.PrevClose as FXRATE, TradeDate from
(select *,max(id) as maxid from aktien GROUP BY
TradeDate,Stock_short order by id desc) s
join rate on s.Stock_Short = rate.`code` where s.id = maxid
group by LocalCurrencyCountry order by TradeDate desc;
SELECT aktien.MarketCap * FXRATE ,rr.fxrate, Marketcap,
aktien.stock_short from aktien join rr on aktien.country =
rr.localcurrencyCountry group by aktien.country;
Here is my attempt at solving this, it contains 3 (!) sub-queries so its not pretty but maybe someone can optimise this.
The first sub-query is for selecting the "fx-rate" row for each country, the second one is for excluding the same "fx-rate" rows from the final result and the third one is to only include the latest market cap value
SELECT stock_short, marketCap * FX.rate, FX.country
FROM aktien a,
(SELECT PrevClose as rate, a3.country
FROM aktien a3 JOIN rate r ON a3.stock = r.code
ORDER BY tradeDate desc LIMIT 1) as FX
WHERE NOT EXISTS (SELECT * FROM rate WHERE code = a.stock)
AND tradeDate = (SELECT MAX(tradeDate) FROM aktien a2 WHERE a2.stock = a.stock)
You would need to do a select and a sub select. The subselect would select the key and MAX(TradeDate) grouped by the key. The outer select would join from that back to the tables on the trade date allowing you get the latest rate for each.
Generic example where the primary key is id, date. If you want specific to your tables please provide more information.
SELECT z.id, z.maxDate, t.rate
FROM (
SELECT id, MAX(date) AS maxDate
FROM table
GROUP BY id
) z
JOIN table t ON z.id=t.id AND z.maxDate=t.date

Wordpress thousand of categories crashing site

I have a big website, at the moment i have about 10k unique visitors daily, I have 2000 categories, 12k Tags, 36k custom taxonomies.
It's not a design flaw, as its a website to watch online movies, I used, categories for Seasons and stuff like that, the custom taxonomies are Actors, regizors etc.
The problem is that my hosting keeps crashing with 100% processor, the resources cannot be an issue, as i have my own server with 4xXeon, 64 GB ram.
I have isolated the problem, and it's due to very slow queries for example, what are my options? :
# Time: 160830 17:01:20
# User#Host: razvypp[razvypp] # localhost []
# Query_time: 9.159090 Lock_time: 0.001680 Rows_sent: 30 Rows_examined: 420117
SET timestamp=1472565680;
SELECT wphn_posts.ID
FROM wphn_posts
INNER JOIN wphn_term_relationships
ON (wphn_posts.ID = wphn_term_relationships.object_id)
WHERE 1=1
AND ( wphn_term_relationships.term_taxonomy_id IN (3630,
4955,4956,4957,4958,4959,4960,4961,4962,4963,4964,4965,
4966,4967,4968,4969,4970,4971,4972,4973,4974,4975,4976,
4977,4978,4979,4980,4981,4982,4983,4984,4985,4986,4987,
4988,4989,4990,4991,4992,4993,4994,4995,4996,4997,4998,
4999,5000,5001,5002,5003,5004,5005,5006,5007,5008,5009,
5010,5011,5012, ... (hundreds of numbers) ...,49740,49779)
Here is a dump of the tables
-- phpMyAdmin SQL Dump
-- version 4.4.15
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: 30 Aug 2016 la 15:17
-- Versiune server: 5.5.51-log
-- PHP Version: 5.5.37
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `trolio`
--
-- --------------------------------------------------------
--
-- Structura de tabel pentru tabelul `wphn_posts`
--
CREATE TABLE IF NOT EXISTS `wphn_posts` (
`ID` bigint(20) unsigned NOT NULL,
`movie_type` int(2) NOT NULL,
`post_author` bigint(20) unsigned NOT NULL DEFAULT '0',
`post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`post_content` longtext NOT NULL,
`post_title` text NOT NULL,
`post_excerpt` text NOT NULL,
`post_status` varchar(20) NOT NULL DEFAULT 'publish',
`comment_status` varchar(20) NOT NULL DEFAULT 'open',
`ping_status` varchar(20) NOT NULL DEFAULT 'open',
`post_password` varchar(20) NOT NULL DEFAULT '',
`post_name` varchar(200) NOT NULL DEFAULT '',
`to_ping` text NOT NULL,
`pinged` text NOT NULL,
`post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`post_content_filtered` longtext NOT NULL,
`post_parent` int(20) unsigned NOT NULL DEFAULT '0',
`guid` varchar(255) NOT NULL DEFAULT '',
`menu_order` int(11) NOT NULL DEFAULT '0',
`post_type` varchar(20) NOT NULL DEFAULT 'post',
`post_mime_type` varchar(100) NOT NULL DEFAULT '',
`comment_count` bigint(20) NOT NULL DEFAULT '0',
`views` int(99) NOT NULL,
`views_this_week` int(5) NOT NULL,
`imdb` double NOT NULL,
`imdb_votes` float NOT NULL,
`imdb_id` varchar(20) NOT NULL,
`fb_shares_root` int(5) NOT NULL,
`movie_name` varchar(140) NOT NULL,
`season` int(2) NOT NULL,
`episode` int(5) NOT NULL,
`serial_id` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structura de tabel pentru tabelul `wphn_term_relationships`
--
CREATE TABLE IF NOT EXISTS `wphn_term_relationships` (
`object_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`term_taxonomy_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`term_order` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structura de tabel pentru tabelul `wphn_term_taxonomy`
--
CREATE TABLE IF NOT EXISTS `wphn_term_taxonomy` (
`term_taxonomy_id` bigint(20) unsigned NOT NULL,
`term_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`taxonomy` varchar(32) NOT NULL DEFAULT '',
`description` longtext NOT NULL,
`parent` bigint(20) unsigned NOT NULL DEFAULT '0',
`count` bigint(20) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `wphn_posts`
--
ALTER TABLE `wphn_posts`
ADD PRIMARY KEY (`ID`),
ADD KEY `post_name` (`post_name`(191)),
ADD KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`),
ADD KEY `post_parent` (`post_parent`),
ADD KEY `post_author` (`post_author`),
ADD KEY `serial_id` (`serial_id`),
ADD KEY `episode` (`episode`),
ADD KEY `season` (`season`),
ADD KEY `movie_name` (`movie_name`);
--
-- Indexes for table `wphn_term_relationships`
--
ALTER TABLE `wphn_term_relationships`
ADD PRIMARY KEY (`object_id`,`term_taxonomy_id`),
ADD KEY `term_taxonomy_id` (`term_taxonomy_id`),
ADD KEY `term_order` (`term_order`);
--
-- Indexes for table `wphn_term_taxonomy`
--
ALTER TABLE `wphn_term_taxonomy`
ADD PRIMARY KEY (`term_taxonomy_id`),
ADD UNIQUE KEY `term_id_taxonomy` (`term_id`,`taxonomy`),
ADD KEY `taxonomy` (`taxonomy`),
ADD KEY `parent` (`parent`),
ADD KEY `count` (`count`),
ADD KEY `term_id` (`term_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `wphn_posts`
--
ALTER TABLE `wphn_posts`
MODIFY `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `wphn_term_taxonomy`
--
ALTER TABLE `wphn_term_taxonomy`
MODIFY `term_taxonomy_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
"Rows examined" = 420K -- That smacks of a missing index.
Probably missing:
INDEX(term_taxonomy_id, object_id)
Please provide SHOW CREATE TABLE for the two tables.
What is the value of innodb_buffer_pool_size?

mysqldump without data without comments without autoincrement JUST CREATE TABLE

When running mysqldump -d I get this format:
--
-- Table structure for table `wp_users`
--
DROP TABLE IF EXISTS `wp_users`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wp_users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_login` varchar(60) NOT NULL DEFAULT '',
`user_pass` varchar(64) NOT NULL DEFAULT '',
`user_nicename` varchar(50) NOT NULL DEFAULT '',
`user_email` varchar(100) NOT NULL DEFAULT '',
`user_url` varchar(100) NOT NULL DEFAULT '',
`user_registered` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_activation_key` varchar(60) NOT NULL DEFAULT '',
`user_status` int(11) NOT NULL DEFAULT '0',
`display_name` varchar(250) NOT NULL DEFAULT '',
PRIMARY KEY (`ID`),
KEY `user_login_key` (`user_login`),
KEY `user_nicename` (`user_nicename`)
) ENGINE=MyISAM AUTO_INCREMENT=722 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = #saved_cs_client */;
/*!40103 SET TIME_ZONE=#OLD_TIME_ZONE */;
How do I get this format:
CREATE TABLE `wp_users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_login` varchar(60) NOT NULL DEFAULT '',
`user_pass` varchar(64) NOT NULL DEFAULT '',
`user_nicename` varchar(50) NOT NULL DEFAULT '',
`user_email` varchar(100) NOT NULL DEFAULT '',
`user_url` varchar(100) NOT NULL DEFAULT '',
`user_registered` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_activation_key` varchar(60) NOT NULL DEFAULT '',
`user_status` int(11) NOT NULL DEFAULT '0',
`display_name` varchar(250) NOT NULL DEFAULT '',
PRIMARY KEY (`ID`),
KEY `user_login_key` (`user_login`),
KEY `user_nicename` (`user_nicename`)
)
I'm trying to compare database structures using diff, but keep getting these lines I have to grep out.
mysqldump -d --compact --compatible=mysql323 ${dbname}|egrep -v "(^SET|^/\*\!)" |sed "s/AUTO_INCREMENT=[0-9]*//g"