可以执行MYSQL SELECT查询以跳过某些特定值

问题描述

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

我要基于以下内容选择表中的所有记录,但是仅当相同的VALUE具有不同的USER并且它不等于0时,然后跳过特定的{{1} }其中VALUE等于0,并取不等于0的那个。

表格数据示例

USER

现在我正在使用|----|------------------|--------| | 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 |----|------------------|--------| 然后使用PHP过滤VALUE之类的

SELECT * FROM TABLE_NAME WHERE (USER = '5' OR USER = '0');

但是使用这种方式会导致在$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; } 分页上出现一些问题

解决方法

在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