当数据表有主键时,使用group by 获取相同字段的最大主键即可,code如下:
SELECT rn.*
FROM table_name rn
WHERE rn.id IN
(
SELECT MAX(r.id)
from table r
GROUP BY a,b,c,d
)
1
2
3
4
5
6
7
8
其中id为表table的主键,a,b,c,d为同时相同时去重的字段。
当数据表没有主键时,需要首先加上主键,使用以下加上主键
SELECT @row:=@row +1 AS id,h.*
FROM table h,(SELECT @row:=0) AS it
1
2
此时执行将产生一列新的值,为id,递增表示主键
然后方法和第一段sql一致。
SELECT rn.*
FROM
(
SELECT @row:=@row +1 AS rownum,h.*
FROM table h,(SELECT @row:=0) AS it
)rn
WHERE rn.rownum IN
(
SELECT MAX(r.rownum)
FROM(
SELECT @row:=@row +1 AS rownum,h.*
FROM table h,(SELECT @row:=0) AS it
)r
GROUP BY a,b,c,d
)
---------------------
【转载】仅作分享,侵删
作者:诺坎普奇迹
原文:https://blog.csdn.net/wangxingfan316/article/details/81132177
|
|