mysql distinct 与 group by

Use database is the need for data de-duplication process, before heard of distinct, after use, that has been done, only to find almost poke a basket in the final test before the line, so there were honestly were filtering in the program , today detailed look.
Establishing a table:
Create Table test_distinct (
name VARCHAR (20 is),
ID int,
address VARCHAR (40)
);
filled data:
INSERT INTO test_distinct values ( 'Lisi', 21 is, 'Beijing');
INSERT INTO test_distinct values ( 'wangwu', 21, 'beijing');
INSERT iNTO test_distinct values ( 'zhaoliu', 21, beijing);
for example, we just want to get id of a person's 21's record, we do not care who he is, where he dwelt when I heard about the use of distinct, he wrote the following sql
the SELECT distinct from the above mentioned id test_distinct;
the result is only 21, very happy, then, want to get to an age of 21 a person, you write the following sql
select distinct id, name from test_distinct;
results get all data. . .
It can not be reconciled, and again with the following sql
select distinct (id), name from test_distinct;
I thought parentheses have been added, and should be, the result is still the same as all of the data. . . .
After Baidu, I realized that the entire column is distinct behind as the basis for deduplication, different name, all naturally select out.
Add the following sentence, test:
INSERT INTO test_distinct values ( 'wangwu', 21, 'nanjing');
SQL query prior to use, the results of only three, it seems that later result Baidu is right.

问题来了,之前的需求怎么解决?

肯定不用distinct了,都试了不好用了,换一个,group by
select name from test_distinct group by id;
OK ,问题解决。
至于他们两个的详细信息,很多大神博客,我就不再赘述了。
Published 20 original articles · won praise 0 · views 10000 +

Guess you like

Origin blog.csdn.net/u011248560/article/details/47404107