IN condition Result Sequence

Source: Internet
Author: User

The IN condition Result sequence problem project needs to record the user's browsing history. My opinion is that the front-end stores the cookie directly, but the front-end says there are too many cookies, so the id must be passed and the back-end returns data, the result is as follows. Www.2cto.com 1. according to the front-end, the array transmission in the url is unordered (I wonder why) 2. the id passed to the backend uses the in condition in the SQL statement, but the returned order is the ascending order of the id, instead of the id sequence passed by the front end. The solution is found on the Internet. The original Article is as follows: there is a scenario where the primary key of a table with tens of thousands of records is id. I want to retrieve several records with IDs of 30, 20, 80, and 40 from the table. Note that the 30, 20, 80, and 40 are in my expected order. I want MySQL to return records in this order. So I write SQL like this: SELECT * FROM my_table WHERE id IN (30, 20, 80, 40); the result is that he did not return IN the order I gave. What should I do? The FIELD () function is found. FIELD (str, str1, str2, str3 ,...) returns the index (position) of str in the str1, str2, str3 ,... list. returns 0 if str is not found. rewrite the SQL statement as: SELECT * FROM my_table WHERE id IN (30, 20, 80, 40) ORDER BY FIELD (id, 30, 20, 80, 40 ); the sorting process is to find the id of the selected records in the FIELD list and return the position based on the position. This usage will lead to Using filesort, which is a very inefficient sorting method. Unless the data changes frequently or has a long cache, we do not recommend that you sort the data in this way. It is a good optimization solution to rearrange the results returned by MySQL in the order of IDs in the memory using PHP.
 

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.