使用最小的数字删除sql中的重复项

问题描述 投票:-1回答:1

我有一个关于SQL的问题。

假设我有一个只有2列的表,它看起来像这样:

col1    col2
--------------
12345   200000
12345   435000
200000  12345
200000  435000
435000  12345
435000  200000
600     1200
600     900
900     600
900     1200
1200    600
1200    900

如何制作它以使结果看起来像这样?

col1    col2
---------------
12345   200000
12345   435000
600     900
600     1200

这背后的逻辑是我希望得到最低的数字作为主要的“关键”。由于12345与200000和435000匹配,并且由于12345是最低的,因此它成为与其他2个数字匹配的主键。

您可以将其视为ID号。 (12345 = 200000 = 435000)&(600 = 900 = 1200)。由于12345是第一组中最低的,600是第二组中最低的,我只想显示12345和600。

我试过了:

select col1, col2
from table_name
where col1<col2

但我有额外的行:

Extra row 1: 200000,435000. 
Extra row 2: 900, 1200.
mysql sql
1个回答
1
投票

您可以使用以下查询

SELECT IF(col1 < col2, col1, col2) col1,
       IF(col1 >= col2, col1, col2) col2
FROM mytable
GROUP BY IF(col1 < col2, col1, col2),
         IF(col1 >= col2, col1, col2)

要得到:

col1    col2
---------------
600     900
600     1200
900     1200
12345   200000
12345   435000
200000  435000

所以,使用上面的派生表:

SELECT MIN(col1) col1,
       col2
FROM (       
   SELECT IF(col1 < col2, col1, col2) col1,
           IF(col1 >= col2, col1, col2) col2
   FROM mytable
   GROUP BY IF(col1 < col2, col1, col2),
            IF(col1 >= col2, col1, col2)
) AS t
GROUP BY col2

给你预期的结果:

col1    col2
---------------
600     900
600     1200
12345   200000
12345   435000

Demo here

© www.soinside.com 2019 - 2024. All rights reserved.