mysql用于选择值按顺序排列的记录

时间:2013-09-18 14:06:18

标签: mysql

如何在TOWN匹配

的情况下选择ID1值依次(两个或更多)的记录

我的表

TOWN    ID1
town1   1
town1   2
town1   4 
town2   1
town2   5 
town2   8 
town3   1 
town3   2 
town3   3 

必填结果

TOWN    ID1
town1   1
town1   2
town3   1 
town3   2 
town3   3 

sql fiddle

http://sqlfiddle.com/#!2/b409f/26

2 个答案:

答案 0 :(得分:6)

您可以使用EXISTS子句检查序列中的下一个值。此代码仅匹配长度为> = 2的“序列”,这似乎是您想要的示例。

SELECT * 
  FROM Table1 a 
 WHERE EXISTS (SELECT * 
                 FROM Table1 b 
                WHERE b.TOWN=a.TOWN 
                  AND b.ID1 IN (a.ID1 - 1, a.ID1 + 1))
 ORDER BY TOWN, ID1

答案 1 :(得分:3)

如果您提出的问题是“向我提供所有具有该城镇相邻id1字段的行”,则只需:

select distinct t1.*
from Table1 t1
join Table1 t2 on t2.town = t1.town and ABS(t1.ID1 - t2.ID1) = 1
order by 1, 2

请参阅SQLFiddle


要在另一列上匹配,请将条件添加到连接,例如:

select distinct t1.*
from Table1 t1
join Table1 t2
  on t2.town = t1.town
  and t2.state = t1.state
  and ABS(t1.ID1 - t2.ID1) = 1
order by 1, 2