Query records with unique fields in a table
Using the Distinct keyword
The Distinct keyword is mainly used to remove duplicate records based on the value of a specified field in the SELECT query record
SELECT DISTINCT [field name] FROM [table name] WHERE [retrieval condition statement]
所以用这样一句SQL就可以去掉重复项了:
SELECT DISTINCT (B) FROM TEST
Or select distinct username from msg;
但是:
这里有一个非常非常需要注意的地方:
SELECT DISTINCT [字段名]后面不能再跟其他的字段,否则检索出来的记录仍然会含有重复项;
错误写法:
SELECT DISTINCT [字段名] ,[其他字段名] FROM [表名] WHERE [检索条件字句]
实际上,我们上面SQL语句结果集里就只有B字段;(一般情况下,这种结果应该是很难满足需求的)
如果我们的记录集里还需要有其他字段值,那怎么办呢?
In fact, we can use another way to solve the problem; just need to use subqueries!
One thing to note when using GROUP BY grouping :
When using a query statement with a GROUP BY clause, the column specified in the SELECT list is either a column specified by GROUP BY, or contains an aggregate group function
所以用这样一句SQL就可以去掉重复项了:
select * from msg group by terminal_id;
so we can get the result set we want: