mysql practical example

1. Group by a field, delete all duplicate data in the group and only leave the row with the maximum value.

    Idea: First group according to a certain field. If the number of rows in the group is greater than 1 row, it means that there are duplicates, then the largest id and grouping field of these rows are selected as the temporary table t 

            Then the temporary table left joins the article table, the condition is that the grouping fields are equal, and the result set of the join table with the largest id is excluded as the temporary table k

            Then select the id value from k;

            Finally, the delete statement deletes these id values.

DELETE article
FROM
	article
	INNER JOIN (
		(
		SELECT
			a.id 
		FROM
			(
				(
				SELECT
					max( id ) AS mid,
					outlink 
				FROM
					`article` 
				WHERE
					type = 3 
					AND outlink IS NOT NULL 
				GROUP BY
					outlink 
				HAVING
					count( id ) > 1 
				) AS t 
			)
			LEFT JOIN article AS a ON t.outlink = a.outlink 
			AND a.id <> t.mid 
		ORDER BY
			a.outlink 
		) AS k 
	) 
WHERE
	k.id = article.id

to be continue...

Guess you like

Origin blog.csdn.net/weixin_37281289/article/details/103974022