Mysql 查询以获取具有空值和重复值的列的不同行

Mysql query to get distinct row with column having null and duplicate values

所以我有一个奇怪的情况,我有一个像这样的 table :

mysql> select * from test;
+-------+------+
| name  | sal  |
+-------+------+
| agent | 1000 |
| agent | 2000 |
| NULL  | 3000 |
| NULL  | 4000 |
| smith | 5000 |
| smith | 6000 |
| neo   | 7000 |
+-------+------+

我想要 return 一个如下所示的数据集:

+-------+------+
| name  | sal  |
+-------+------+
| agent | 1000 |
| NULL  | 3000 |
| NULL  | 4000 |
| smith | 5000 |
| neo   | 7000 |
+-------+------+

意思是我想在 name 重复的地方获取唯一的行,但是当 name 为 null 或不重复时按原样获取所有行。

为了实现这一点,我在下面编写了这个查询,它运行良好。但是我想优化一下。

select * 
from test 
where sal in (
                select sal from ( 
                        select min(sal) as sal 
                        from test 
                        group by name 
                    union 
                        select sal 
                        from test where name is null 
                ) t 
order by sal);

创建此示例数据的查询 -

create table test (name text, sal int);
insert into test values ('agent',1000);
insert into test values ('agent',2000);
insert into test values (null,3000);
insert into test values (null,4000);
insert into test values ('smith',5000);
insert into test values ('smith',6000);
insert into test values ('neo',7000);

有人可以帮我吗?我知道我们不应该使用 IN 来获取数据,因为这会在生产中大量增加查询时间。

感谢任何帮助!

您可以尝试对 UNION ALL 使用两个查询,一个是针对值 is null 的名称,另一个是按名称写入 MIN 聚合函数而不是 [=14] =].

查询#1

SELECT *
FROM (
  SELECT name,sal
  FROM test
  WHERE name IS NULL
  UNION ALL
  SELECT name,min(sal)
  FROM test
  WHERE name IS NOT NULL
  group by name
)t1
ORDER BY sal;
name sal
agent 1000
3000
4000
smith 5000
neo 7000

View on DB Fiddle

备注

您可以尝试在 name 列上创建索引,这可能有助于您提高查询性能