Oracle SQL连接使用like并强制转换为varchar2

时间:2019-05-16 12:32:32

标签: sql oracle join casting

我需要join几张桌子。其中一列有变音符号(例如áíé...),但第二列没有变音符号,在某些记录中有后缀。假设:

Table A:                               Table B:

code  |  name  |  surname              name     |  username
-------------------------              --------------------
1234  |  John  |  Doé                  Doe      |  Doe
5678  |  Jane  |  Smith                Doe      |  DoeJ
9012  |  Tom   |  Novák                Dean Doe |  DoeD

我需要在joinsurnameusername这两个表,并且我需要显示表B中可以与表A中的记录匹配的所有记录。表A中特定code -s的列表。 因此,如果我的代码列表仅是1234,我的select应该返回类似的内容:

A.name  |  A.surname  |  B.username
-----------------------------------
John    |  Doé        |  Doe
John    |  Doé        |  DoeJ
John    |  Doé        |  DoeD

现在我有这个select

select A.name, A.surname, B.username
  from (select column_value as code
    from SYS.ODCIVARCHAR2LIST('1234', '5678', '9012', '3456')) t
right join tableA A on t.code = A.code
join tableB B
  on replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(p.prijmeni, 'Ě', 'E'), 'Š', 'S'), 'Č', 'C'), 'Ř', 'R'), 'Ž', 'Z'), 'Ý', 'Y'), 'Á', 'A'), 'Í', 'I'), 'É', 'E'), 'Ú', 'U'), 'Ů', 'U'), 'Ď', 'D'), 'Ň', 'N'), 'Ó', 'O'), 'Ť', 'T')
    like (B.username || '%')
where t.code is not null;

结果只有一条记录:

A.name  |  A.surname  |  B.username
-----------------------------------
John    |  Doé        |  Doe

当我删除(注释)t.code is not null子句中的where时,我得到了部分正确的结果:

A.name  |  A.surname  |  B.username
-----------------------------------
John    |  Doé        |  Doe
null    |  null       |  DoeJ
null    |  null       |  DoeD

但是表B中有成百上千条我不想在结果中显示的记录。

有人可以帮助我吗?我知道,这个概念是错误的,但这不是我的工作,我现在需要纠正它。

2 个答案:

答案 0 :(得分:0)

您将'%'添加到错误的一面,这应该可行:

select A.name, A.surname, B.username
  from (select column_value as code
    from SYS.ODCIVARCHAR2LIST('1234', '5678', '9012', '3456')) t
right join tableA A on t.code = A.code
join tableB B
  on B.username
  LIKE replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(p.prijmeni, 'Ě', 'E'), 'Š', 'S'), 'Č', 'C'), 'Ř', 'R'), 'Ž', 'Z'), 'Ý', 'Y'), 'Á', 'A'), 'Í', 'I'), 'É', 'E'), 'Ú', 'U'), 'Ů', 'U'), 'Ď', 'D'), 'Ň', 'N'), 'Ó', 'O'), 'Ť', 'T') || '%'
where t.code is not null;

答案 1 :(得分:0)

使用

on B.username LIKE utl_raw.cast_to_varchar2(nlssort(A.surname, 'nls_sort=binary_ai'))

在您的加入条件下。    nlssort调用将重音字符转换为其语言基础,并在比较时忽略大小写。