How to use the reverse order of self-increasing ID when MySQL has where condition

< H1 > description < / H1 >

first of all, there is a table with a table structure of

CREATE TABLE `article_like` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT "id",
  `article_id` int(10) unsigned NOT NULL COMMENT "id",
  `user_id` int(10) unsigned NOT NULL COMMENT "id",
  `create_at` datetime NOT NULL COMMENT "",
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_article_id_user_id` (`article_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT="";

A user can only like an article once, so the article id and user id are uniquely indexed.

< H1 > sample data < / H1 >



SQL ID explain

explain

ID


explain

< H1 > here comes the problem < / H1 >
what I want to ask this time is how to build this index in this scenario. My idea now is to set up two indexes. One is to make a unique index with the article id and the user id, and then to create a separate index with the article id. But in this way, MySQL will still choose the previous unique index. This question will be used in many scenarios. If there are comrades who know, can you help solve
?

SELECT id,article_id,user_id
FROM article_like 
WHERE article_id = 1 
ORDER BY id DESC
LIMIT 20 

this query uses article_id, so Mysql chooses the uniq_article_id_user_id index, but this index does not contain id, so order by will not use the index, you can try to add id to the first item of the index, so you can combine the where statement with the ORDER BY statement to meet the leftmost prefix, and your index will be used.

CREATE TABLE `article_like` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  `article_id` int(10) unsigned NOT NULL COMMENT 'id',
  `user_id` int(10) unsigned NOT NULL COMMENT 'id',
  `create_at` datetime NOT NULL COMMENT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_article_id_user_id` (`id`,`article_id`,`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='';



try adding FORCE INDEX (PRIMARY)


to the table name with an article_id,id,user_id federated index

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3481c-2b698.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3481c-2b698.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?