自联接以选择连续的数字

时间:2010-03-09 09:28:18

标签: mysql

CREATE TABLE `mybug` (
  `SEAT_NO` decimal(2,0) NOT NULL,
  `ROW_NO` decimal(2,0) NOT NULL,
  `COL_NO` decimal(2,0) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `mybug` VALUES ('1','1','1'),('26','7','2'),('31','8','2'),('32','8','1'),('33','9','1'),('34','9','2'),('35','9','5'),('36','9','6'),('37','10','6'),('38','10','5'),('39','10','2'),('40','10','1'),('41','11','1'),('42','11','2'),('43','11','4'),('44','11','5');

+---------+--------+--------+
| SEAT_NO | ROW_NO | COL_NO |
+---------+--------+--------+
|       1 |      1 |      1 | 
|      26 |      7 |      2 | 
|      31 |      8 |      2 | 
|      32 |      8 |      1 | 
|      33 |      9 |      1 | 
|      34 |      9 |      2 | 
|      35 |      9 |      5 | 
|      36 |      9 |      6 | 
|      37 |     10 |      6 | 
|      38 |     10 |      5 | 
|      39 |     10 |      2 | 
|      40 |     10 |      1 | 
|      41 |     11 |      1 | 
|      42 |     11 |      2 | 
|      43 |     11 |      4 | 
|      44 |     11 |      5 | 
+---------+--------+--------+
16 rows in set (0.00 sec)

在上图中,我需要选择2个位于同一行的座位,并且列号彼此相邻。 对于例如座位号码38&即使两个座位都来自同一行,也不能发出39,因为列号为2& 5不相邻。

预期结果如下:

31
33
35
37
39
41
43

这些是起始号码,下一个座位也将自动预订。例如31& 32

3 个答案:

答案 0 :(得分:2)

SELECT m1.seat_no
FROM   mybug m1
       JOIN mybug m2
         ON m1.row_no = m2.row_no
WHERE  m1.seat_no < m2.seat_no
       AND Abs(m1.col_no - m2.col_no) = 1; 

答案 1 :(得分:0)

这应该做你需要的:

SELECT a.seat_no 
FROM mybug as a, mybug as b 
WHERE a.row_no = b.row_no 
    AND b.col_no = a.col_no +1

答案 2 :(得分:0)

select m1.SEAT_NO, m2.SEAT_NO
from mybug m1, mybug m2
where m1.ROW_NO=m2.ROW_NO
AND ABS(m1.COL_NO-m2.COL_NO)=1