我如何加入 ID 号与列表字符串 ID [重复]
Posted
技术标签:
【中文标题】我如何加入 ID 号与列表字符串 ID [重复]【英文标题】:how can i join with an id number vs list string id [duplicate] 【发布时间】:2017-10-26 06:11:59 【问题描述】:我有表 1:id 是一个整数,
表 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?
【问题讨论】:
正确的解决方案是修复您的数据模型。不要在单个列中存储多个逗号分隔值。 谢谢,我知道,我刚刚选择,我没有插入数据库 【参考方案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
【讨论】:
谢谢,我一直在解决问题!【参考方案2】:试试:
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)
【讨论】:
【参考方案3】:不要将值存储为字符串列表。
使用集合和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 |
【讨论】:
以上是关于我如何加入 ID 号与列表字符串 ID [重复]的主要内容,如果未能解决你的问题,请参考以下文章