简体   繁体   中英

SQL Query join with more than one table with relation one-to-many

I have following tables:

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)

I want to select destination data, with category and activity WHERE:

  • One destination can have many category (tbl_destination one-to-many tbl_destination_category)
  • One destination can have many activity (tbl_destination one-to-many tbl_destination_activity)

My expected output example:

---------------------------------------------------------------------------------------------------------------------
Destination name Category Activity
---------------------------------------------------------------------------------------------------------------------
Mount Everest Mountain, nature Hiking, Trekking, Camping



Is this possible to do in one single query? or whats the most efficient query?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM