0

我有两张桌子:

表:商店

----------------------------------------------
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)之间加入。作为一个集合和作为数字字段stores的表,我不能使用“in”关键字。material_cat_idsmaterial_categorymaterial_cat_id

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

4

3 回答 3

3

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

StoreMaterialCategory

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

然后从商店中删除 Material_Cat_IDs。我在此处放置了一个示例模式,其中包含几个演示查询,以展示如何获得您可能需要的 2 个输出。

但是,如果您坚持使用此表结构,那么您可以像这样进行连接:

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

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;

例子

于 2012-07-05T09:03:05.060 回答
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);

输出

制定出示例SQLFIDDLE

于 2012-07-05T09:32:10.367 回答
0

也许是这样的?

select *
from stores
inner join material_category
on ',' + stores.material_cat_ids + ',' LIKE '%,' + CONVERT(varchar(100), material_category.material_cat_id) + ',%'
于 2012-07-05T08:57:02.277 回答