i have a table with hotel data, each row has an hotel id. in 2 more tables (hotel images + hotel facilities) there are multiple lines corresponding to each single row in the main table (based on the hotel id value).
I am trying to join multiple tables into a json result.
the wanted outcome is:
"{
"hotels" : [
{
"ID": 1,
"name": "hotelA",
"star_rating": 5,
"Address": "a",
"isRefundable": true,
"images":[
{"url":"x", "title":"a", "description":"a"},
{"url":"x", "title":"b", "description":"b"},
{"url":"x", "title":"c", "description":"c"},
{"url":"x", "title":"d", "description":"d"},
],
"facilities":[
{"facilityID": 1, "facilityName":"free wifi"},
{"facilityID": 2, "facilityName":"free breakfast"},
{"facilityID": 3, "facilityName":"TV"},
]
},
{...},{...},{...}
]}"
currently I've implemented this via code, is there a way to do this using an sql procedure? im using (microsoft sql)
im adding my schema underneath
Main Table (Hotel Table):
| ID | name | star_rating | Address | isRefundable |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | hotelA | 5 | a | true |
| 2 | hotelB | 5 | b | true |
| 3 | hotelC | 3 | c | true |
| 4 | hotelD | 4 | d | true |
| 5 | hotelE | 5 | e | false |
Images Table:
HotelID | url | title | description |
---|---|---|---|
1 | x | a | a |
1 | x | b | b |
1 | x | c | c |
1 | x | d | d |
2 | x | a | a |
2 | x | b | b |
2 | x | c | c |
3 | x | a | a |
3 | x | b | b |
4 | x | a | a |
5 | x | b | b |
Facilities Table:
HotelID | facilityID | facilityName |
---|---|---|
1 | 1 | free wifi |
1 | 2 | free breakfast |
1 | 3 | TV |
3 | 1 | free wifi |
3 | 3 | TV |
5 | 4 | MiniFridge |
I have tried the following but it did not get me very far, because it did not handle multiple lines matching a single line between tables, so h got just one image/facility per hotel - and not all of the related rows.
BEGIN
SET NOCOUNT ON;
SELECT hotel.*, facility.FacilityId, facility.FacilityName, img.url, img.title, img.description,
FROM [main_hotel_table] hotel
JOIN db.facilityTable facility ON hotel.HotelId = facility.HotelId
JOIN db.ImageTable img ON hotel.HotelId = img.HotelId
FOR JSON Path, ROOT('hotels')
END
is there a way to do this using an sql procedure?
1条答案
按热度按时间kupeojn61#
You must try something like this: