我如何加入id号码与列表字符串id

时间:2017-10-26 06:12:00

标签: oracle

我有表1:id是一个数字int,

表2包含引用ID 1,如下所示:'1,2,3 ...',您可以在下面看到更多详细信息:

WITH TB1 AS(
     SELECT 1 ID FROM DUAL UNION ALL
     SELECT 2 ID FROM DUAL UNION ALL
     SELECT 3 ID FROM DUAL
), TB2 AS
(
   SELECT 'A' NAMES, '1,2' IDREF FROM DUAL
)
SELECT t1.*, t2.Names FROM TB1 t1 join tb2 t2 on t1.id in t2.idref

如何通过id in?

加入tb1 vs tb2

3 个答案:

答案 0 :(得分:1)

您可以使用LIKE运算符加入,其中包含一个小技巧:

SELECT t1.*
FROM TB1 t1
INNER JOIN TB2 t2
    ON ',' || t2.IDREF || ',' LIKE '%,' || t1.ID || ',%'

ID=1为例,此处的想法是查找,1,以下CSV字符串:

,1,2,

我们可以在IDREF列前添加和发布逗号,以确保每个隔离的ID值都由双方的逗号分隔。然后,只需搜索给定的,ID,,并在两边都使用逗号。

Demo

答案 1 :(得分:1)

尝试:

WITH TB1 AS(
     SELECT 1 ID FROM DUAL UNION ALL
     SELECT 2 ID FROM DUAL UNION ALL
     SELECT 3 ID FROM DUAL
), TB2 AS
(
   SELECT 'A' NAMES, '1,2' IDREF FROM DUAL
)                                                                                       
select T1.*, T2.*
from TB1 T1 
    join TB2 T2 on T1.id in (select regexp_substr(T2.IDREF,'[^,]+', 1, level) as list from dual
                                            connect by regexp_substr(T2.IDREF, '[^,]+', 1, level) is not null)         

答案 2 :(得分:0)

不要将值存储为字符串列表。

使用集合和MEMBER OF运算符:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TYPE IntList IS TABLE OF INTEGER

查询1

WITH TB1 ( ID ) AS (
     SELECT 1 FROM DUAL UNION ALL
     SELECT 2 FROM DUAL UNION ALL
     SELECT 3 FROM DUAL
),
TB2 ( names, idref ) AS (
   SELECT 'A', IntList( 1,2 ) FROM DUAL
)
SELECT t1.*,
       t2.Names
FROM   TB1 t1
       join tb2 t2
       on t1.id MEMBER OF t2.idref

<强> Results

| ID | NAMES |
|----|-------|
|  1 |     A |
|  2 |     A |

或者将您的列表分成自己的表,以便您可以正确引用TB1的外键:

查询2

WITH TB1 ( ID ) AS (
     SELECT 1 FROM DUAL UNION ALL
     SELECT 2 FROM DUAL UNION ALL
     SELECT 3 FROM DUAL
),
TB2 ( names ) AS (
   SELECT 'A' FROM DUAL
),
TB3 ( names, idref ) AS (
   SELECT 'A', 1 FROM DUAL UNION ALL
   SELECT 'A', 2 FROM DUAL
)
SELECT t1.*,
       t2.Names
FROM   TB1 t1
       join tb3 t3
       on t1.id = t3.idref
       join tb2 t2
       on t2.names = t3.names

<强> Results

| ID | NAMES |
|----|-------|
|  1 |     A |
|  2 |     A |