在MySQL数据库中,我存储了一组数字,只给出了第一个和最后一个,例如:
id | from | to 1 | 65.789 | 66.323 2 | 66.151 | 69.298 etc...
我试图用PHP和MySQL找出一种方法来找到不止一次存在的数字,例如:在上面,数字从66.151到66.323。
答案 0 :(得分:3)
SELECT a.from, b.to FROM mytable a JOIN mytable b ON a.from BETWEEN b.from AND b.to
答案 1 :(得分: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) )
答案 2 :(得分: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
) ;