Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从多对多关系创建可能的组合列表_Sql_Sql Server - Fatal编程技术网

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

Sql 从多对多关系创建可能的组合列表,sql,sql-server,Sql,Sql Server,我有一套桌子 酒店 国家/地区 地区 城市 酒店类型 还有一个名为Mappings的多对多关系表,其中包含所有包含类似 id, hotel_id, reference_type, reference_id, ... 其中,参考类型可以是国家,地区,城市,酒店类型等 而reference\u id是所述实体的id,如country\u id或city\u id等 我需要创建一个列表,列出所有可能的 Country_Name+Hotel_Type_Name Region_Name+Hotel_Ty

我有一套桌子

酒店
国家/地区
地区
城市
酒店类型

还有一个名为
Mappings
的多对多关系表,其中包含所有包含类似

id, hotel_id, reference_type, reference_id, ...
其中,
参考类型
可以是
国家
地区
城市
酒店类型
等 而
reference\u id
是所述实体的id,如
country\u id
city\u id

我需要创建一个列表,列出所有可能的

Country_Name+Hotel_Type_Name
Region_Name+Hotel_Type_Name
City_Name+Hotel_Type_Name

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

我在这里暗示了几件事,但您可以通过这种方式进行内部联接:

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)

这将列出
Country\u Name+Hotel\u Type\u 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
地区名称+酒店类型名称
城市名称+酒店类型名称
可以使用类似的SQL查询