【问题标题】:How to implement MySQL statement similar like loop?如何实现类似循环的MySQL语句?
【发布时间】:2011-12-11 02:50:32
【问题描述】:

我有一个 table1,有如下字段。

rsid  pos
123   10000
234   10001
567   10008

另一个table2只有一个字段

rsid
123
345
...

所以,我的目标是找到位置在一定范围内的 rsid。 例如,我想在table1中查找rsid,其位置在table2中rsid的±10000位置内,例如123。

我可以为特定的行编写sql,如下所示

select *
from table1
where pos > (select pos from table1 where rsid=123)-100000
  and pos < (select pos from table1 where rsid=123)+100000; 

但是在table2中,有数千行,最后我想将所有合格的rsid合并到一个表中,有没有像for循环一样的方法来合并所有结果? 非常感谢您的帮助?

更新:
感谢您的回复。一个更具体的例子如下。假设 table1 只有以下条目。

rsid  pos
123   10000
234   10001
567   10008
100   20015
101   20001
108   50000

另一个table2只有这样的条目。

rsid
123
100

那么预期的结果是

rsid  pos
234   10001
567   10008
101   20001

因为 234,567 在 123 的 +-10000 范围内,而 101 在 101 的 +-10000 范围内。

【问题讨论】:

    标签: mysql sql loops union


    【解决方案1】:

    必须承认:我不太明白这个问题。 所以这就是我认为你的意思:

    1) 查找特定 RSID 的 100,000 范围内的所有 RSID

    2) 将这些结果创建到一个新表中。 (如果您只是使用 select 语法中的 create table,则不需要循环和联合。

    3) 不确定 table2 与任何事情有什么关系,但我认为您只想要 table1 和 table2 中都存在的 RSID 位置。

        Create table NEWTable
        Select RSID, pos
        from table1 t1
        INNER JOIN table2 t2 on t1.RSID = T2.RSID
        WHERE t1.pos between  
          (select pos from table1 where rsid=123)-100000 
      and (select pos from table1 where rsid=123)+100000; 
    

    【讨论】:

    • 至于t2,其实我只需要找到t2中100,000个RSID内的所有RSID
    • 样本数据会有所帮助。以及一些预期的结果。我相信 T1、T2 之间的连接会为您提供这些 ID。但是,如果 T1 中不存在 T2 中的条目,则连接会消除它们,反之亦然,所以我仍然不确定您在追求什么。
    • 感谢您的友好回复。一个更具体的例子如下。假设 table1 只有以下条目。 rsid pos 123 10000 234 10001 567 10008 100 20015 101 20001 108 50000 和另一个 table2 只有这样的条目。 rsid 123 100 那么预期结果将是 rsid pos 234 10001 567 10008 101 20001,因为 234,567 在 123 的 +-10000 范围内,而 101 在 101 的 +-10000 范围内。
    【解决方案2】:
    select t1.pos from 
    (select distinct t1.pos from t1 join t2 
     where t1.pos between t2.pos-20000 and t2.pos+20000) t1 
    where t1.pos not in (select * from t2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-09
      • 2018-07-04
      • 1970-01-01
      • 2018-12-22
      • 2023-03-23
      • 2016-01-19
      • 2013-04-08
      • 2014-12-14
      相关资源
      最近更新 更多