Assume that the table my_tbl contains three fields A, B, and C. Now we need to query the minimum value of Column B under each different value of column A in the table.
For example, the table record is: A B C 1 3 'cd' 2 3 'nhd' 1 5 'bg' 2 6 'cds' 1 7 'kiy' 3 7 'Password' 3 8 'ndf'
Expected result: A B C 1 3 'cd' 2 3 'nhd' 3 7 'Password'
(1) One method is to first find the minimum value of B under each a value, and then query all records that meet the requirements based on these minimum values. The statement for querying SQL statements that meet the minimum B value is as follows:
Select a. * From my_tbl as a where a. B = (select Min (B) from my_tbl as B where B. A = A. ); Because of the nested query and intersection, the intermediate results were not calculated for an hour in the case of 0.8 million records (I doubt where I wrote the error ); the record quantity will not be discussed later.
(2) The above method is a disaster and can only be discarded. The specific logic is: first group by column A and column B, and then select the record with the smallest column B value in each group to generate the result set. The SQL statement is written as follows:
SelectA, B, C, count ()From (select a, B, c from my_tbl group by a, B) as a group By; After the query is executed, it takes only 1.1 seconds.
Once again, it is proved that different SQL query policies can directly lead to huge performance differences.
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.