One SQL statement of MySQL queries the SQL statements of some result instances of all different types of products.

Source: Internet
Author: User

One SQL statement of MySQL queries the SQL statements of some result instances of all different types of products.

For & ever

 

 

Consider the following scenarios:
There is a product table with many product records. The table contains the product type field prodtype, which is used to indicate different product types. There are 10 different product types, for example.

 

Requirements:
Sort by product ID using an SQL statement to query the latest five of the 10 different types of products.

For example, the following table records:
1 prodtypea
2 prodtypeb
3 prodtypea
4 prodtypea
5 prodtypea
6 prodtypeb
7 prodtypea
8 prodtypea
9 prodtypea

 

You need to use an SQL statement to query the following result set:

9 prodtypea
8 prodtypea
7 prodtypea
5 prodtypea
4 prodtypea
6 prodtypeb
2 prodtypeb

 

 

After discussing with xinxinran today, the result is as follows :::

You can use the following SQL query:
Select ID, prodtype from product A where (select count (1) from product B where a. prodtype = B. prodtype and B. ID> = A. ID) <= 5

What if we want to obtain the oldest five records?
Modify B. ID> = A. ID to B. ID <= A. ID, as shown below:
Select ID, prodtype from product A where (select count (1) from product B where a. prodtype = B. prodtype and B. ID <= A. ID) <= 5

 

@ Forandever for & ever

Related Article

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.