SQL Query与多个具有一对多关系的表连接

时间:2017-04-08 22:11:30

标签: mysql join optimization

我有以下表格:

tbl_destination

id_destination INT PRIMARY
destination_name VARCHAR(200)

tbl_destination_category

id_destination_category INT PRIMARY
id_destination INT
id_category INT

tbl_destination_activity

id_destination_activity INT PRIMARY
id_destination INT
id_activity INT

tbl_category

id_category INT PRIMARY
category_name VARCHAR(200)

tbl_activity

id_activity INT PRIMARY
activity_name VARCHAR(200)

我想选择目的地数据,包括类别和活动WHERE:

  • 一个目的地可以有多个类别(tbl_destination一对多tbl_destination_category)
  • 一个目的地可以有很多活动(tbl_destination一对多tbl_destination_activity)

我的预期输出示例:

----------------------------------------------- -------------------------------------------------- --------------------
目的地名称 类别 活动
-------------------------------------------------- -------------------------------------------------- -----------------
珠穆朗玛峰 山,自然 徒步旅行,徒步旅行,露营



这可以在一个查询中完成吗?或者最有效的查询是什么?

1 个答案:

答案 0 :(得分:0)

you would have more than one row per relationships, but your SQL is here:

 select td.destination_name,  tc.category_name, ta.activity_name
 from tbl_destination td
 inner join tbl_destination_category tdc on tdc.id_destination = td.id_destination 
    iiner join tbl_destination_activity tda on tda.id_destination = td.id_destination 
    iiner join tbl_category tc on tc.id_category = tdc.id_category 
    inner join tbl_activity ta on ta.id_activity  = tda.id_activity