【问题标题】:MySql match get record where columns value near others (under threshold)MySql匹配获取列值靠近其他列的记录(低于阈值)
【发布时间】:2020-06-01 20:14:28
【问题描述】:

我有以下坐标记录

我想要的是,获取 z1 与任何其他记录的差异小于 4(阈值)的所有记录

这意味着在上表中,最后 2 条记录的差异小于 4,然后我想在查询中获取它们。

如果存在z1 = 808 的新记录,则应该返回该记录和id 为28478 的记录,因为它们的差异小于4。

有什么方法可以在 MySql 中实现这一点吗?

或者也许是 PHP,不用说这么久?

编辑: 这是数据:

+-------+-------+-------+-------+-------+
|  id   |  x1   |  x2   |  z1   |  z2   |
+-------+-------+-------+-------+-------+
| 28478 | -1500 | -1496 |   804 |   808 |
| 29929 | -1500 | -1496 |  1444 |  1448 |
| 30051 | -1500 | -1496 | -1168 | -1164 |
| 30346 | -1500 | -1496 |  -336 |  -332 |
| 28039 | -1496 | -1492 | -1128 | -1124 |
| 28969 | -1496 | -1492 | -1424 | -1420 |
| 29265 | -1496 | -1492 |  -520 |  -516 |
| 29872 | -1496 | -1492 |  1288 |  1292 |
| 30122 | -1496 | -1492 |  -932 |  -928 |
| 30846 | -1496 | -1492 |  1376 |  1204 |
| 30898 | -1496 | -1492 |  1380 |  1384 |
+-------+-------+-------+-------+-------+

我试过了

select *
from coordinates t
where 
    x1 between -1500 and -1500 + 4
  and exists (
        select 1
        from coordinates t1
        where t1.id <> t.id
          and abs(t1.z1 - t.z1) <= 4);

但没用。

【问题讨论】:

标签: php mysql sql algorithm select


【解决方案1】:

你可以使用exists:

select t.*
from mytable t
where exists (
    select 1 
    from mytable t1
    where t1.id <> t.id and abs(t1.z1 - t.z1) <= 4
)

不使用abs()可能更有效:

select t.*
from mytable t
where exists (
    select 1 
    from mytable t1
    where t1.id <> t.id and t1.z1 - t.z1 between -4 and 4
)

Demo on DB Fiddle - 两个查询都产生:

编号 | x1 | x2 | z1 | z2 ----: | ----: | ----: | ---: | ---: 30846 | -1496 | -1492 |第1376章1204 30898 | -1496 | -1492 | 1380 | 1384

【讨论】:

  • 我试过了,但没有用,我已经编辑了我的问题并插入了数据和查询,你能检查一下吗?
  • 请解释您所说的不起作用是什么意思。我用您的示例数据为我的答案添加了一个小提琴:查询确实返回了所需的结果。
  • 好的我发现了问题,我应该在查询和子查询中添加x1 between -1500 and -1500 + 4,如下所示:select t.* from coordinates t where x1 between -1500 and -1500 + 4 and exists ( select 1 from coordinates t1 where x1 between -1500 and -1500 + 4 and t1.id &lt;&gt; t.id and abs(t1.z1 - t.z1) &lt;= 4 );,因为提供的记录只是其中很多记录的一部分表,但是是的,所以谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多