方法一:使用mod()
mod(a,b) 在sql中的意思是 a / b 的余数
mod(id, 2)=1 是指id是奇数。
mod(id, 2)=0 是指id是偶数。
select * from employees
where mod(emp_no, 2) = 1 and last_name <> 'Mary'
order by hire_date desc;
1
2
3
4
方法二:使用%
如id是奇数:(id % 2) = 1;
id是偶数:(id % 2) = 0;
select * from employees
where emp_no % 2 = 1 and last_name <> 'Mary'
order by hire_date desc;
1
2
3
方法三:使用&
如id是奇数:(id & 1) = 1;
id是偶数:(id & 1) = 0;
select * from employees
where emp_no & 1 = 1 and last_name <> 'Mary'
order by hire_date desc;
1
2
3
判断偶数也可以使用如 id = (id >> 1 << 1),先除2,再乘2,和原来的值相等就是偶数,不等就是奇数;
上面的方法只能判断全是数字的情况,如果数字中出现其他字符,如*,就不能用上面的方法判断了,这时候可以使用==正则表达式==
借鉴:https://blog.csdn.net/ccStroy/article/details/78061861
查询奇数
select * from employees
where emp_no regexp '[13579]$';
1
2
查询偶数
select * from employees
where emp_no regexp '[02468]$'
1
2
解释一下:
^a :以 a 为开头;
a$ :以a结尾;
. :匹配任何字符;
[abc]:[字符集合],包含中括号里的字符;
[^abc]:不包含中括号里的字符;