2

在 MySQL 数据库中,我存储了仅给出第一个和最后一个的数字集,例如:

编号 | 来自 | 至
1 | 65.789 | 66.323
2 | 66.151 | 69.298
ETC...

我试图用 PHP 和 MySQL 找出一种方法来找到不止一次存在的数字,例如在上面,从 66.151 到 66.323 的数字。

4

3 回答 3

3
SELECT a.from, b.to FROM mytable a JOIN mytable b ON a.from BETWEEN b.from AND b.to
于 2012-08-04T22:16:34.103 回答
2

我会这样做:

select 
    IF(
    t1.`from` = t2.`from` and t1.`to` = t2.`to`,
    CONCAT('ID: ',t1.id, ' (',t1.`from` ,'-',t1.`to`,') is same as ID: ',t2.id,' (',t2.`from`,'-',t2.`to`,')' ),    
    IF(
        t1.`from` >= t2.`from` and t1.`to` <= t2.`to`,
        CONCAT('ID: ',t1.id, ' (',t1.`from` ,'-',t1.`to`,') is included in ID: ',t2.id,' (',t2.`from`,'-',t2.`to`,')' ),
        CONCAT('ID: ',t1.id, ' (',t1.`from` ,'-',t1.`to`,') overlaps with ID: ',t2.id,' (',t2.`from`,'-',t2.`to`,')' )
    )
) as overlaping
from 
    numbers t1 
join 
    numbers t2 
where 
    t2.`from` <= t1.`to` 
and 
    t2.`to` >= t1.`to` 
and 
    t1.id != t2.id
group by 
    concat( greatest(t1.id,t2.id),'-',least(t1.id, t2.id) )
于 2012-08-04T22:25:32.357 回答
1
SELECT 
    GREATEST(a.from, b.from) AS overlap_start
  , LEAST(a.to, b.to)        AS overlap_end
FROM mytable a 
  JOIN mytable b 
    ON  a.id < b.id
    AND a.from <= b.to
    AND b.from <= a.to ;

和另一个选项,使用分组,以便组合一些结果并产生更少的行:

    SELECT 
        MIN(b.from) AS overlap_start
      , a.to        AS overlap_end
    FROM mytable a 
      JOIN mytable b 
        ON  a.id <> b.id
        AND a.from <= b.from
                  AND b.from <= a.to
                            AND a.to <= b.to
    GROUP BY a.id 
  UNION ALL
    SELECT 
        b.from AS overlap_start
      , b.to   AS overlap_end
    FROM mytable b 
    WHERE EXISTS
          ( SELECT *
            FROM mytable a
            WHERE a.id <> b.id
              AND a.from <= b.from
                               AND b.to <= a.to
          ) ;
于 2012-08-04T22:59:58.367 回答