在 MySQL 数据库中,我存储了仅给出第一个和最后一个的数字集,例如:
编号 | 来自 | 至 1 | 65.789 | 66.323 2 | 66.151 | 69.298 ETC...
我试图用 PHP 和 MySQL 找出一种方法来找到不止一次存在的数字,例如在上面,从 66.151 到 66.323 的数字。
SELECT a.from, b.to FROM mytable a JOIN mytable b ON a.from BETWEEN b.from AND b.to
我会这样做:
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) )
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
) ;