我是数据库和 mysql 的新手,正在尝试了解如何设计我的数据库。我正在开展测试项目,人们可以在其中查看某些橱柜中的元素。因此,用户可以单击一个柜子并查看其中的所有架子以及每个架子的所有元素。
到目前为止,我已经确定我需要下表:
Item Table
Item ID, Item Name
Shelf Table
Shelf ID, Shelf Number
Cabinet Table
Cabinet ID, Cabinet Name
我所困惑的是我需要什么关系表?我确信这对某人来说真的很容易!
我可以有第四张 table ,里面有类似的东西:
ItemID, Shelf ID, Cabinet ID
这是否有意义,以便我可以查询柜子中的所有架子及其每个架子的元素?我确信这个问题很容易回答,但我的脑子很痛!我被告知如果有帮助的话可以使用 MyIsam 作为存储引擎。
谢谢
编辑:
谢谢,如果您不介意的话,还有一个问题。你知道如何获取所有货架中的所有商品,以便它们出现在 html 中,如下所示:
<div id="shelf-1"><p>spoon</p><p>fork</p>
<div id="shelf-2"><p>knife</p></div>
我有以下似乎有效的内容,但通过阅读周围的内容,我认为在查询中循环不是一个好的做法:
$cabinetID = $_GET['cabinetid'];
$sqlShelf = sprintf(' SELECT shelf_id
FROM shelf
INNER JOIN cabinet ON (cabinet.cabinet_id = shelf.cabinet_id)
WHERE cabinet.cabinet_id = %s', $cabinetID);
$resultShelf = mysql_query($sqlShelf);
while($shelf = mysql_fetch_assoc($resultShelf)) {
$shelfID = $shelf['shelf_id'];
$sqlItem = sprintf('SELECT *
FROM item
INNER JOIN shelf ON (item.shelf_id = shelf.shelf_id)
INNER JOIN cabinet ON (cabinet.cabinet_id = shelf.cabinet_id)
WHERE cabinet.cabinet_id = %s
AND shelf.shelf_id = %s', $cabinetID, $shelfID);
$resultItem = mysql_query($sqlItem);
echo('<div>');
while($item = mysql_fetch_assoc($resultItem)) {
echo('<p>' . $item['item_name'] . '</p>' . PHP_EOL);
}
echo('</div>');
最佳答案
在编写 SQL 之前先用英语来思考。
你可以有很多柜子;每个柜子有零个或多个搁板;每个架子上可以有零个或多个元素。
一个架子一次只能位于一个柜子中;一件元素一次只能放在一个架子上。
因此,我将其设计为三个表,其中两个表具有一对多关系。
CREATE TABLE IF NOT EXISTS cabinet
(
cabinet_id bigint not null auto_increment,
primary key(cabinet_id)
);
CREATE TABLE IF NOT EXISTS shelf
(
shelf_id bigint not null auto_increment,
cabinet_id bigint,
primary key(shelf_id),
foreign key(cabinet_id) references cabinet(cabinet_id) on delete cascade on update cascade
);
CREATE TABLE IF NOT EXISTS item
(
item_id bigint not null auto_increment,
shelf_id bigint,
primary key(item_id),
foreign key(shelf_id) references shelf(shelf_id) on delete cascade on update cascade
);
这是一个示例查询,它将为您提供特定柜子中的所有项目(刚刚尝试过 - 效果很好):
SELECT item.item_id, cabinet.cabinet_id
FROM item
INNER JOIN shelf ON (item.shelf_id = shelf.shelf_id)
INNER JOIN cabinet ON (cabinet.cabinet_id = shelf.cabinet_id)
关于mysql - 帮助mysql的数据库设计结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6083376/