Using Mysql's DISCTINCT group by query does not duplicate records _mysql
Source: Internet
Author: User
There is a demand, has not been resolved, in Google for a long time, given the scheme is not a can be used, and finally got it done.
So, suppose a table:
ID f_id Value
1 2 A
2 2 b
3 5 C
4 9 C
5 9 A
6 6 D
ID f_id Value
1 2 A
2 2 b
3 5 C
4 9 C
5 9 A
6 6 D
ID is the primary key, F_ID is a foreign key, I need to get the data that does not duplicate the foreign key f_id, if using group by or distinct is easy to handle
Select f_id from table GROUP by f_id
SELECT DISTINCT f_id from table
But if you want to get the ID value in the result, it will be messy anyway. For example, I want to sort the results with IDs, such as "SELECT DISTINCT f_id, id from table order by id DESC" completely in vain. Looking at a lot of examples on Google, I found it necessary to tamper with IDs in select to let MySQL know what to do with IDs in addition to f_id. such as Max, Min, Avg,sun. Is OK, so the code that becomes the following is done ...
Select F_ID, max (ID) as ID from table group by f_id ORDER by id DESC
OK, there is an article on the Internet very close to the answer, but he did not "as ID", resulting in my MySQL execution results in error, hehe.
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