Order. Making my request work very slowly

I have a sql query as follows

select *
from incidents
where remote_ip = '192.168.1.1' and is_infringement = 1
order by reported_at desc
limit 1;

This request currently takes 313.24 seconds to run.

If I delete order by, therefore the request

select *
from incidents
where remote_ip = '192.168.1.1' and is_infringement = 1

it only takes 0.117 seconds to start.

The report_at column is indexed.

So, 2 questions, firstly, why is it taking so long with this order_by expression, and secondly, how can I speed it up?

EDIT: In response to the questions below, you can get an explanation:

'1', 'SIMPLE', 'incidents', 'index', 'uniqueReportIndex,idx_incidents_remote_ip', 'incidentsReportedAt', '4', NULL, '1044', '100.00', 'Using where'

And the create statement of the table:

CREATE TABLE `incidents` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `incident_ip_id` int(10) unsigned DEFAULT NULL,
  `remote_id` bigint(20) DEFAULT NULL,
  `remote_ip` char(32) NOT NULL,
  `is_infringement` tinyint(1) NOT NULL DEFAULT '0',
  `messageBody` text,
  `reported_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Formerly : created_datetime',
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniqueReportIndex` (`remote_ip`,`host_id_1`,`licence_feature`,`app_end`),
  UNIQUE KEY `uniqueRemoteIncidentId` (`remote_id`),
  KEY `incident_ip_id` (`incident_ip_id`),
  KEY `id` (`id`),
  KEY `incidentsReportedAt` (`reported_at`),
  KEY `idx_incidents_remote_ip` (`remote_ip`)
)

Note: I skipped some of the irrelevant fields, so there are more indexes than fields, but you can safely assume that the fields for all indexes are listed in the table

+4
1

EXPLAIN , - ORDER BY MySQL incidentsReportedAt. , , WHERE. , , . .

Update

OP reported_at report_ip ( , . ), 313 133 . , . , , is_infringement = 1 WHERE, .

OP :

Ok (remote_ip, reported_at) (0,083 ).

, remote_ip = '192.168.1.1' . uniqueReportIndex. , reported_at MySQL, , , ORDER BY, , .

, MySQL (remote_ip, reported_at) (WHERE remote_ip = '192.168.1.1') (ORDER BY reported_at DESC). WHERE -, .

.
, , , OP .


reported_at report_ip , EXPLAIN . .

reported_at, report_ip is_infringement ( ).

MySQL ( WHERE ORDER BY) ). - SELECT *.

( ) incidentsReportedAt. ; , . ( reported_at ).


is_infringement = 1. , , , . , .

, , , (, , cron ..).

+2
source

Source: https://habr.com/ru/post/1681850/


All Articles