MySQL从to选择id并排除开始和结束id

时间:2019-05-22 10:17:20

标签: mysql

我有桌子:

+----+-------------------+----------+
| id | channel           | channels |
+----+-------------------+----------+
| m2 | AA-AA             |        4 |
| 1  | TT_1              |        4 |
| 2  | TT_2              |        4 |
| 11 | TT_3              |        4 |
| 12 | TT_4              |        4 |
| m4 | BB-BB             |        4 |
| m3 | CC-CC             |        4 |
| m5 | DD-DD             |        4 |
| 17 | FF-FF             |        4 |
| m1 | EE-EE             |        4 |
+----+-------------------+----------+

在此示例中,我需要查询m2并获取结果到下一个起始ID m,不包括m2和m4 ...因此我的Ajax将其发送到mysql:

http://server_ip/get_bouquets/m2

并且需要得到结果:

1
2
11
12

如果客户端发送到服务器:

http://server_ip/get_bouquets/m5

它需要得到结果:

17

我尝试过: 在此处查询显示

SELECT id, channel, channels FROM tables WHERE id BETWEEN 'm2' AND '%m%' but i got empty results...any help will be welcome.

谢谢。

1 个答案:

答案 0 :(得分:2)

如果您确实有某种方法可以保证事件的顺序(我在这里使用auto_increment字段进行模拟),则可以发现第一个和下一个序列号并对其进行测试

DROP table if exists t;
create table t
(sno int auto_increment primary key, id varchar(2),channel varchar(20));
insert into t (id,channel) values
('m2'  , 'AA-AA'),             
( '1'  , 'TT_1' ) ,            
( '2'  , 'TT_2' ) ,                    
( '11' , 'TT_3' ),                      
( '12' , 'TT_4' ),                     
( 'm4' , 'BB-BB'),                     
( 'm3' , 'CC-CC'),                     
( 'm5' , 'DD-DD'),                     
( '17' , 'FF-FF'),                     
( 'm1' , 'EE-EE');

select id 
from t
where sno > (select sno from t where id = 'm2') and sno < 
(select sno from t t1 where left(id,1) = 'm' and sno > (select sno from t where id = 'm2') limit 1);

+------+
| id   |
+------+
| 1    |
| 2    |
| 11   |
| 12   |
+------+
4 rows in set (0.00 sec)