How MySQL is sorted by specific ID

Source: Internet
Author: User
How MySQL is sorted by specific ID


SET foreign_key_checks=0;--------------------------------Table structure for ' P '------------------------------DROP TABLE IF EXISTS ' P '; CREATE TABLE ' P ' (' id ' int (one) not null auto_increment, ' name ' varchar (255) Default NULL, ' categories_id ' int (one) DEFA Ult NULL, PRIMARY KEY (' id ')) engine=myisam auto_increment=7 DEFAULT Charset=utf8;--------------------------------Reco RDS of P------------------------------insert INTO ' P ' values (' 1 ', ' Jimmy ', ' 2 '); INSERT INTO ' P ' values (' 2 ', ' Tina ', ' 2 ')  Insert INTO ' P ' values (' 3 ', ' dd ', ' 2 ') and insert INTO ' P ' values (' 4 ', ' Hello ', ' 2 '); INSERT INTO ' P ' values (' 5 ', ' World ', ' 2 '); INSERT into ' P ' VALUES (' 6 ', ' Slucky ', ' 2 '); SET foreign_key_checks=0;--------------------------------Table structure for ' p_sort '----------------------------- -drop TABLE IF EXISTS ' p_sort ';  CREATE TABLE ' p_sort ' (' categories_id ' int () NOT null default ' 0 ', ' best_sort_person_id ' varchar ') default NULL, PRIMARY KEY (' categories_id ')) Engine=myisam DEFAULTCharset=utf8;--------------------------------Records of p_sort------------------------------INSERT into ' p_sort ' VALUES (' 2 ', ' 2,5,1 ');


Reply to discussion (solution)

SELECT * from P, p_sort  

Find_in_set (P.id, p_sort.best_sort_person_id) >0 desc is used to row id=2,5,1 in front
Find_in_set (P.id, p_sort.best_sort_person_id) ASC is used to arrange the id=2,5,1 in the order in which they appear

Thank you, xuzuning, for being mad.

SELECT p.* from  P INNER joins P_sort s on p.categories_id=s.categories_id    ORDER by IF (Find_in_set (Id,s.best_sort_ person_id) >0,find_in_set (id,s.best_sort_person_id), id) ASC;
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.