选择查询,将集合字段与其他表号字段一起加入

时间:2012-07-05 08:23:02

标签: sql oracle

我有两张桌子:

表:商店

----------------------------------------------
store_cd    store_nm    active    material_cat_ids
---------------------------------------------
L           Store(L)    Y         20,5
B           Store(B)    Y         7

和 表:Material_category

----------------------------------------------------------
material_cat_id    name                        active
----------------------------------------------------------
20                 Material Category type A    Y
5                  Material Category type B    Y
7                  Material Category type C    Y

现在我需要在两个表(storesmaterial_category)之间加入。如果storesmaterial_cat_ids作为集合而material_category表格中有material_cat_id作为数字字段,我就不能使用“in”关键字。

请建议加入这些表格的最佳方式。

3 个答案:

答案 0 :(得分:3)

将您的材料类别ID存储为字符串是一个糟糕的主意。如果还为时已晚,请回到绘图板!你正在打败关系数据库的目的。一个更好的表结构将是一个新表,如:

StoreMaterialCategory

Store_CD (FK Stores), 
Material_Cat_ID (FK Material_Category), 
Primary Key --> (Store_CD, Material_Cat_ID)

然后从商店中删除Material_Cat_IDs。我已经将一个示例模式Here与几个演示查询放在一起,以展示如何获得您可能需要的两个输出。

但是,如果你坚持这个表结构,那么你可以像这样进行连接:

SELECT  Store_nm, Name
FROM    Stores
        INNER JOIN material_Category
            ON ',' || material_Cat_ids || ',' LIKE '%,' || CAST(material_Cat_ID AS VARCHAR(5)) || ',%';

<强> Example On SQL Fiddle

修改

如果您需要列表中的类别,可以使用:

SELECT  Store_nm, 
        LISTAGG(Name, ',') WITHIN GROUP (ORDER BY Name) AS Categories
FROM    Stores
        INNER JOIN material_Category
            ON ',' || material_Cat_ids || ',' LIKE '%,' || CAST(material_Cat_ID AS VARCHAR(5)) || ',%'
GROUP BY Store_nm;

<强> Example

答案 1 :(得分:2)

create table store (store_cd  varchar2(20),store_nm varchar2(20),active  varchar2(1),material_cat_ids varchar2(200));

Insert into STORE
   (STORE_CD, STORE_NM, ACTIVE, MATERIAL_CAT_IDS)
 Values
   ('L', 'Store(L)', 'Y','20,5');
Insert into STORE
  (STORE_CD, STORE_NM, ACTIVE, MATERIAL_CAT_IDS)
 Values
  ('B', 'Store(B)', 'Y', '7');


create table Material_category(material_cat_id number ,name varchar2(20),active varchar2(1));

insert into material_category values(20,' A','Y');
insert into material_category values( 5,' B','Y' );
insert into material_category values(7,'C','Y');

WITH tab as (
SELECT  DISTINCT store_cd
       ,store_NM
       ,active
       ,REGEXP_SUBSTR (material_cat_ids, '[^,]+', 1,LEVEL) material_cat_id
FROM store s
CONNECT BY REGEXP_SUBSTR (material_cat_ids, '[^,]+', 1, LEVEL) IS NOT NULL
  ) 
SELECT * from tab t 
             ,material_category mc 
where t.material_cat_id=to_char(mc.material_cat_id);

output

制定了示例SQLFIDDLE

答案 2 :(得分:0)

也许是这样的?

select *
from stores
inner join material_category
on ',' + stores.material_cat_ids + ',' LIKE '%,' + CONVERT(varchar(100), material_category.material_cat_id) + ',%'