2016-09-19 85 views
0

我有一些基本的SQL問題,我已經做了錯誤的事情。所以我想問一下這是什麼方法來完成的。 我有房間的桌子。房間有房間大小,名字和牆壁的顏色。房間裏有傢俱桌子,它可以有很多傢俱。將多個傢俱連接到房間的正確方法是什麼?例如:在SQL中存儲數據的正確方法

Room Table 
roomID: 5 
size: 15 
wallColor: Blue 
haveFurniture: 2,4,5 //This is the part I`m not sure about 

Furniture Table 
furnitureID 2 
type: table 
color: wood 

Furniture Table 
furnitureID 4 
type: closet 
color: wood 

etc... 

那麼,什麼是正確的方式來連接傢俱的空間。用戶可以創建多個房間和多個傢俱

+1

你要再來一臺壁球下來在一些SQL方言,稱每'Room'和'furnitureId'一行結合表。 –

+0

由於@GordonLinoff提到您需要在房間和傢俱之間創建M:M關係,爲此,您需要一個表(可以稱之爲RoomFurniture),其中包括RoomId和FurnitureId。 –

回答

1

創建多到多(nm)的關係表加盟二。根據你的符號:

RoomHasFurnature Table 
roomID 5 
furnitureID 2 

RoomHasFurnature Table 
roomID 5 
furnitureID 4 

RoomHasFurnature Table 
roomID 5 
furnitureID 5 

然後,你會使用連接來拉出數據。這是一個粗略的例子:

SELECT * FROM Room 
LEFT JOIN RoomHasFurnature USING(roomID) 
INNER JOIN Furniture USING(furnatureID) 

這會給每個傢俱項目一行。你可以用GROUP_CONCAT()

SELECT r.*, GROUP_CONCAT(f.type) FROM Room AS r 
LEFT JOIN RoomHasFurnature USING(roomID) 
INNER JOIN Furniture AS f USING(furnatureID) 
1

你應該廣告關係表命名如:room_forniture爲參加各個房間的各個forniture

Room Table 
roomID: 5 
size: 15 
wallColor: Blue 


Room_forniture Table 
rooID: 5 
fornitureID = 2 

Room_forniture Table 
rooID: 5 
fornitureID = 4 

Room_forniture Table 
rooID: 5 
fornitureID = 5 


Furniture Table 
furnitureID 2 
type: table 
color: wood 

Furniture Table 
furnitureID 4 
type: closet 
color: wood 
...... 
相關問題