php - 可以执行 MYSQL SELECT 查询以跳过某些特定值
问题描述
是否有任何可能的方法从表中选择具有指定值的重复值,并跳过另一个?
我想根据下表选择表中的所有记录,但只有当相同的记录VALUE
不同USER
且不等于0时,然后跳过特定等于0的记录VALUE
,USER
取不等于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
解决方案
在 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
推荐阅读
- python - 我该如何解决 KeyError: 'ir.actions.view' odoo?
- javascript - 使用 redux-form 上的字段数组计算总计和小计
- node.js - 将用户名和其他数据传递给 socket.io 连接
- r - 倾向得分匹配使用 Match 命令估计二元结果变量中的 ATT
- java - 在JAVA的嵌套for循环中,为什么小循环中的大循环比大循环中的小循环更快?
- node.js - 在节点js中部分更新mongodb中嵌套对象数据的最佳方法
- java - Java GWT 应用程序 - 编译有时有效,有时无效
- android - 按住时带有粉红色背景的 RatingBar
- php - 参数必须是数组或对象,在第45行的process.php中实现了Countable,“if(count($result)==1)”有问题
- html - 将选择器转换为 CSS 中的样式