请教大家一个SQL语句:表T结构:
字段a(number) 字段b(varchar)
1 10
1 13
0 aa字段a只能是1或0。当为1时,字段b为数字;为0时,字段b为字符现要求查出:字段b的值在10至20之间的记录
字段a(number) 字段b(varchar)
1 10
1 13
0 aa字段a只能是1或0。当为1时,字段b为数字;为0时,字段b为字符现要求查出:字段b的值在10至20之间的记录
调试欢乐多
字段a(number) 字段b(varchar)
1 10
1 13
0 aa
为什么 你在1#贴出的表中 包含了 aa需求到底是什么 b字段只能是数字而且在10到20之间嘛
select * from tb
where a=1
and to_number(b)>=10
and to_number(b)<=20
SQL> ed
已写入 file afiedt.buf 1 CREATE TABLE t(
2 a NUMBER,
3 v varchar(5)
4* )
SQL> /表已创建。SQL> ed
已写入 file afiedt.buf 1* INSERT INTO t VALUES(1,'10')
SQL> /已创建 1 行。SQL> ed
已写入 file afiedt.buf 1* INSERT INTO t VALUES(1,'13')
SQL> /已创建 1 行。SQL> ed
已写入 file afiedt.buf 1* INSERT INTO t VALUES(0,'aa')
SQL> /已创建 1 行。SQL> select * from t; A V
---------- -----
1 10
1 13
0 aaSQL> ed
已写入 file afiedt.buf 1 select * from t
2* WHERE a = 1 AND v <=20 AND v >=10
SQL> / A V
---------- -----
1 10
1 13SQL>
with t1 as(
select 1 a, '10' b from dual
union
select 1 a, '13' b from dual
union
select 0 a, 'aa' b from dual
)
select a,b from t1 where t1.b>='10' and t1.b<='30';
注意:<= 右面的数据哦!要用单引号哦!负责会报数据类型错误哦!因为oracle 首先会根据 b的数据类型来判断b=等号右边的值哦!再会根据<进行判断类型的哦!
with t1 as(
select 1 a, '10' b from dual
union
select 1 a, '13' b from dual
union
select 0 a, 'aa' b from dual
)
select * from t1 where
a = 1 and b between '10' and '20'
select *
from table
where
a=1
and
b>='10' and b<='20'
1、对于下面这种,同类型的两个字段,我新建一个表,此种查询是正常的,但在我真实表中,却老报类型错误。
select * from tb
where a=1
and to_number(b)>=10
and to_number(b)<=20
2、对于此种,不会报错,但查询结果不对,它比较的不是数字,而是字符:select *
from table
where
a=1
and
b>='10' and b<='20'
试一下>='5',就查不出来了,它是根据字符一个个的进行对比的
在对一个字符类型的数据,进行数值,类型进行查询时,oracle 内部就会根据你等号右边的值来相应的给你设置左边字段的数据类型,所以对于:
with t1 as(
select 1 a, '10' b from dual
union
select 1 a, '13' b from dual
union
select 0 a, 'aa' b from dual
)
select a,b from t1 where t1.b>='10' and t1.b<='30';
sql是可以满足你的需求的,对于按照你常理的思维模式来说,你会接受不了!因为你想,你的数据类型是字符型的,而你要用字符类型的字段来和一个取值范围大小的数值类型来比较,你感觉这个公式应该是不成立的对吧,但是对于对于任何语言来说,大于号和小于号,都是对一个数来进行操作的!所以你只要使用了!<> 那么想对而言,你操作的条件就已经是数值型了!
楼上,请把语句改成这样试试:select a,b from t1 where t1.b>='5' and t1.b<='30';
select 1 a, '10' b from dual
union
select 1 a, '13' b from dual
union
select 0 a, 'aa' b from dual
)
select * from (
select a,b from t1 where trim(translate(b,'0123456789',' ')) is null
)f where to_number(b)>5 and to_number(b)<20
我把原表(T)拷贝一份(C):
create table C as select * from T;用这样的测试语句:select * from C where a=1 and to_number(b)>=10 and to_number(b)<=20
完全正常可在我原表里,使用上面的语句还是报“无效数字”,使用楼上的也一样感觉拷贝出来的表,除了一些外键约束、索引等外,没有其它的不同了(后来把原表的这些删掉,还是报错)
不能满足你的需求,真不搞不懂!--创建表
create table t
(
a number,
b varchar(10)
)--插入数据
insert into t value
(select 1 a, '10' b
from dual
union
select 1 a, '13' b
from dual
union
select 0 a, 'aa' b from dual)
--查询表数据
select * from (
select a,b from t where trim(translate(b,'0123456789',' ')) is null
)f where to_number(b)>5 and to_number(b)<20 ;
select * from C where a=1 and to_number(b)>=10 and to_number(b)<=201、创建一个同类型的新表,使用上面的可以2、直接拷贝原表生成的表,使用上面的也可以3、就是在原表查不行(原表是使用PowerDesigner生成的,可能有些特殊)