Ungrouped fields can be omitted after mysql group by

Quoted from: http://blog.csdn.net/wxwzy738/article/details/20636563

 

The use of group by in mysql is very different from that of Oracle. To be precise, it is not only the same as the difference between Oracle and other databases, but it does not follow standard SQL. We know that conventional sql must be combined with aggregate functions for group by, and the selected fields must appear in group by in addition to aggregate functions, otherwise an error will be reported, but this function is extended in mysql
. For the sql of the aggregate function, its function combines the limit to obtain the result. When you think about it carefully, it is a bit like the Oracle analytical function. When the limit is used, the maximum and minimum values ​​are not obtained, but the number of the group by result set. One line, which is equivalent to the first group by, and then limit 1 under each group by.
Secondly, when I said that when the conventional group by is combined with the aggregation function, the selected fields must exist in the group by except for the aggregation function, but this is not the case in mysql, which has the function of implicit fields, for example:

Table data:



 Execute statement:

SELECT * FROM `tb_demo2` GROUP BY `name`

 result:



 Execute again:

SELECT * FROM `tb_demo2` GROUP BY `name`,id

 

 

Execute again:

SELECT GROUP_CONCAT(id),name FROM `tb_demo2` GROUP BY `name`

 

 

Use a sql statement to delete duplicate data in the table and keep one:

select a.* FROM tb_demo2 a WHERE EXISTS (select 1 FROM tb_demo2 WHERE name = a.name GROUP BY name HAVING count(name) > 1) AND id NOT in(SELECT id FROM `tb_demo2` GROUP BY `name` HAVING count(name) >1)

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326801498&siteId=291194637