在SQL中存储数据的正确方法

时间:2016-09-19 11:06:33

标签: mysql sql database

对于我做错了的事情,我有基本的SQL问题。所以我想问一下实现这个目标的正确方法是什么。 我有房间桌。房间有房间大小,名称和墙壁颜色。客房配有家具,可以摆放许多家具。什么是将多个家具连接到房间的正确方法。例如:

SELECT MATCH (username) AGAINST ('shaharyar' IN NATURAL LANGUAGE MODE) AS `score`, 
       uid, first_name, username, `status`, created
FROM users
WHERE uid <> 164125 -- to prevent self profile search
HAVING score > 0
ORDER BY score DESC, created DESC;

那么,将家具连接到房间的正确方法是什么。用户可以创建多个房间和多个家具

3 个答案:

答案 0 :(得分:1)

您应该使用名为eg:room_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
 ......

答案 1 :(得分:1)

创建一个多对多(n-m)关系表来加入这两者。根据您的表示法:

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()

将其压缩为某些SQL方言
SELECT r.*, GROUP_CONCAT(f.type) FROM Room AS r
LEFT JOIN RoomHasFurnature USING(roomID)
INNER JOIN Furniture AS f USING(furnatureID)

答案 2 :(得分:0)

寻找多对多数据模型。您将需要另一张桌子来保持房间和家具之间的关系。还要寻找归一化 - 非规范化。

https://en.wikipedia.org/wiki/Many-to-many_(data_model)