按字段值连接表中的多行

时间:2012-05-19 07:38:17

标签: sql

我有一个像这样的company行:

id(int)  |name(string)  |maincategory(int)  |subcategory(string)    
1        |Google        |1                  |1,2,3
2        |yahoo         |4                  |4,1

和其他表category一样:

 id(int) |name(string)  
 1       |Search
 2       |Email
 3       |Image
 4       |Video

我想通过company.subcategory = category.id

加入两个表格

可以在sql中使用吗?

5 个答案:

答案 0 :(得分:2)

splitting your subcategory column开始。最后,您应该有一个额外的company_category表,其中company_id和category_id为列。

 company_id(int) |category_id(int)  
 1               |1
 1               |2
 1               |3
 2               |4
 2               |1

答案 1 :(得分:0)

您的设计无效。你应该有另一个名为companySubcategories的表或类似的东西。 这个表有两列companyId是categoryId。 然后您的选择将如下所示:

select <desired fields> from
company c
join companySubcategories cs on cs.companyId = cs.id
join category ct on ct.id = cs.categoryId

答案 2 :(得分:0)

你可以在下面做...

select * from 
company c, category cc
where c. subcategory like '%'||cc.id||'%';

它在oracle数据库中按预期工作..

答案 3 :(得分:0)

您可以引入新表company_subcategory来跟踪子类别

  id (int) | subcategory(int)
    1      |    1
    1      |    2
    1      |    3
    2      |    1
    2      |    4

然后你就可以运行select as

 select company.name AS company, category.name AS category 
   FROM company 
           JOIN company_subcategory 
                ON company.id = company_subcategory.company  
           JOIN category 
                ON company_subcategory.subcategory = category.id;

获取

+---------+----------+
| company | category |
+---------+----------+
| google  | search   |
| google  | email    |
| google  | image    |
| yahoo   | search   |
| yahoo   | video    |
+---------+----------+

答案 4 :(得分:0)


SELECT *
  FROM COMPANY CMP, CATEGORY CT
 WHERE (SELECT CASE
                 WHEN INSTR(CMP.SUB_CATEGORY, CT.ID) > 0 THEN
                  'TRUE'
                 ELSE
                  'FALSE'
               END
          FROM DUAL) = 'TRUE'

此查询使用INSTR函数在SUB_CATEGORY中查找ID。 如果确实存在,则返回该行。

输出如下


ID  NAME   MAIN_CATEGORY  SUB_CATEGORY   ID    NAME
1   Google  1             1,2,3        1    Search
1   Google  1             1,2,3        2    Email
1   Google  1             1,2,3        3    Image
2   yahoo   2             4,1          1    Search
2   yahoo   2             4,1          4    Video

希望它有所帮助。

但是,我建议你避免使用这种类型的条目,因为ID应该有单独的条目而不是组合条目。这可能会在将来产生问题,所以现在最好避免它。