首页 > 解决方案 > 可以执行 MYSQL SELECT 查询以跳过某些特定值

问题描述

是否有任何可能的方法从表中选择具有指定值的重复值,并跳过另一个?

我想根据下表选择表中的所有记录,但只有当相同的记录VALUE不同USER且不等于0时,然后跳过特定等于0的记录VALUEUSER取不等于0的记录。

示例表数据:

|----|------------------|--------|
| ID | VALUE            | USER   |
|----|------------------|--------|
| 1  | HELLO WORLD      | 0      | <--- Skip This
|----|------------------|--------|
| 2  | HELLO WORLD 2    | 0      | <--- Take This
|----|------------------|--------|
| 3  | HELLO WORLD      | 5      | <--- Take This
|----|------------------|--------|
| 4  | WELCOME MY WORLD | 0      | <--- Skip This
|----|------------------|--------|
| 5  | WELCOME MY WORLD | 5      | <--- Take This
|----|------------------|--------|

现在我正在使用SELECT * FROM TABLE_NAME WHERE (USER = '5' OR USER = '0'); Then 使用 PHP 来过滤 VALUE 之类的

$newData = array();
foreach($data as $key => $val){
      if($val['USER'] == 5){
            $newData[] = $val;
            unset($data[$key]);
      }
      continue;
}

foreach($data as $key => $val){
      if(in_array($val['VALUE'], array_column($newData, "VALUE"))) continue;
      $newData[] = $val;
}

但是使用这种方式会导致分页出现一些问题limit

标签: phpmysqlsubquerygreatest-n-per-groupwindow-functions

解决方案


在 SQL 中,您可以使用not exists它。我认为你想要的逻辑是:

select t.*
from mytable t
where 
    user = 5 
    or (
        user = 0 
        and not exists (select 1 from mytable t1 where t1.value = t.value and t1.user = 5)
    )

相关子查询可能是一个更简单的解决方案:

select t.*
from mytable t
where user = (
    select max(t1.user)
    from mytable t1
    where t1.value = t.value and t1.user in (0, 5)
)

在 MySQL 8.0 中,您还可以使用窗口函数:

select *
from (
    select t.*, row_number() over(partition by value order by user desc) rn
    from mytable
    where user in (0, 5)
) t
where rn = 1

推荐阅读