我在一个名为"数字"的表格中有一个9位数的ID列表,其中一列名为" ID"。我想在子查询中使用它们来查找名为artransaction的表中的特定行。问题是在artransaction的transactionid列中,它在9位ID前面有一个零。
所以,如果我这样做:
select * from artransaction
where transactionid in lpad((select id from numbers where rownum=1),10,'0');
结果回来了。但如果我这样做:
select * from artransaction
where transactionid in lpad((select id from numbers),10,'0');
它说"单行子查询返回多行"
是否可以在LPAD中放入子查询?
答案 0 :(得分:1)
您应该重写该查询。这是一个基于Scott的EMP表的示例 - 我想选择包含COMM的行,看起来像那些存储在NUMBERS表中的行。
SQL> select ename, comm from emp order by ename;
ENAME COMM
---------- ----------
ALLEN 300
BLAKE
CLARK
FORD
JAMES
JONES
KING
MARTIN 1400
MILLER
SMITH
TURNER 0
WARD 500
12 rows selected.
SQL>
示例NUMBERS表:
SQL> create table numbers (comm number);
Table created.
SQL> insert into numbers values (14);
1 row created.
SQL> insert into numbers values (50);
1 row created.
SQL> insert into numbers values (3);
1 row created.
SQL> select * From numbers;
COMM
----------
14
50
3
SQL>
测试:
SQL> -- This one will work because of the ROWNUM = 1 condition, which returns a single value
SQL> select * from emp
2 where comm in rpad((select comm from numbers where rownum = 1), 4, '0');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ---------- ---------- ---------- ----------
7654 MARTIN SALESMAN 7698 28.09.1981 1250 1400 30
SQL> -- This will result in error because NUMBERS contain several values
SQL> select * from emp
2 where comm in rpad((select comm from numbers), 4, '0');
where comm in rpad((select comm from numbers), 4, '0')
*
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row
SQL> -- So - rewrite it
SQL> select * from emp
2 where comm in (select rpad(comm, 3, '0') from numbers);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ---------- ---------- ---------- ----------
7521 WARD SALESMAN 7698 22.02.1981 1250 500 30
7499 ALLEN SALESMAN 7698 20.02.1981 1600 300 30
SQL>
或者,应用于您的查询:
select * from artransaction
where transactionid in (select lpad(id, 10, '0') from numbers);