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

It is possible do a MYSQL SELECT query to skip some specific value

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

我想select根据下面的table中的所有记录,但只有当相同的VALUE有不同的USER并且不等于0,则跳过具体的VALUE其中USER等于0,取不等于0的

示例Table数据:

|----|------------------|--------|
| 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'); 然后使用 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

的分页出现一些问题

在 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中,您还可以使用window函数:

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