Use disctinct group by of MySQL to query non-Repeated Records

Source: Internet
Author: User

There was a demand that had not been solved. After searching for half a day on Google, none of the solutions provided could be used. Finally, the ghost was able to solve the problem.
Suppose a table:

Id f_id Value
1 2
2 2 B
3 5 C
4 9 C
5 9
6 6 d

Id f_id Value
1 2
2 2 B
3 5 C
4 9 C
5 9
6 6 d
ID is the primary key, f_id is the foreign key, and I need to obtain data of the non-repeated foreign key f_id. It is easy to do this with group by or distinct.

Select f_id from Table group by f_id
Select distinct f_id from table
However, if you want to get the id value in the result, it will be messy anyway. For example, I want to sort the results by ID, such as "select distinct f_id, ID from Table order by ID DESC. I have read a lot of examples on Google and found that I need to do some operations on the ID in the SELECT statement to let MySQL know what operations should be performed on the ID except f_id. Such as Max, Min, AVG, and sun .. are all possible, so it becomes the followingCodeIt's done ......

Select f_id, max (ID) as ID from Table group by f_id order by ID DESC
Well, there isArticleVery close to the answer, but he does not have "as ID", resulting in incorrect execution results in my MySQL.

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.