创建可能的组合列表从多对多关系

时间:2017-02-20 09:20:40

标签: sql sql-server

我有一套表格

Hotels Countries Regions Cities Hotel_Types

以及名为Mappings的多对多关系表,其中包含所有包含

等信息的关系/映射
id, hotel_id, reference_type, reference_id, ...

其中reference_type可以是CountryRegionCityHotel_Typereference_idcountry_idcity_id等所述实体的ID。

我需要创建一个

的所有可能组合的列表
Country_Name+Hotel_Type_Name
Region_Name+Hotel_Type_Name
City_Name+Hotel_Type_Name

酒店存在的地方。任何帮助我如何访问不同表中的名称以及如何组合它们

2 个答案:

答案 0 :(得分:0)

我在这里暗示一些事情,但你可以用这种方式进行内部联接:

select name, hotel_type_name 
from (select c.country_name as name, h.hotel_type_name Mappings m inner join Countries c on m.reference_type='Country' and m.reference_id=c.country_id inner join hotel_Types h on m.reference_type='Hotel_type' and m.reference_id=h.hotel_type_id)  union all 
     (select c.region_name as name, h.hotel_type_name Mappings m inner join Regions r on m.reference_type='Region' and m.reference_id=r.region_id  inner join Hotel_Types h on m.reference_type='Hotel_type' and m.reference_id=h.hotel_type_id) union all
     (select c.city_name as name, h.hotel_type_name Mappings m inner join Cities ci on m.reference_type='City' and m.reference_id=ci.city_id inner join Hotel_Types h on m.reference_type='Hotel_type' and m.reference_id=h.hotel_type_id)

答案 1 :(得分:0)

这将列出Country_Name+Hotel_Type_Name

的唯一组合
--link hotels to hotel_type
with Hotel_Hotel_Types as (
  select h.hotel_id
    ,ht.reference_id as hotel_types_id
  from Hotels as h
  inner join Mappings ht on ht.reference_type = 'Hotel_Type' and h.hotel_id = ht.hotel_id
)
--link hotels to Country_Name
,Hotel_Country_Name as (
  select h.hotel_id
    ,c.reference_id as countries_id
  from Hotels as h
  inner join Mappings c on c.reference_type = 'Country' and h.hotel_id = c.hotel_id
)
select distinct ht.*, c.*
from Hotel_Hotel_Types hht
  inner join Hotel_Types ht on ht.hotel_types_id = hht.hotel_types_id
  inner join Hotel_Country_Name hc on hc.hotel_id = hht.hotel_id
  inner join Countries c on с.countries_id = hc.countries_id

Region_Name+Hotel_Type_NameCity_Name+Hotel_Type_Name可以使用类似的sqls进行查询。