2011-05-21 77 views
0

我是新来的数据库和MySQL,并试图让我的头如何设计我的数据库。我正在测试项目,人们可以查看他们在某些橱柜中的物品。因此用户可以点击一个橱柜并查看其中的所有货架以及每个货架的所有物品。帮助数据库设计结构为mysql

到目前为止,我已经工作了,我需要下表:

Item Table 
Item ID, Item Name 

Shelf Table 
Shelf ID, Shelf Number 

Cabinet Table 
Cabinet ID, Cabinet Name 

位我卡上是我需要什么样的关系表?我确信这对某个人来说非常简单!

我能有持有像第四台:

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>'); 

回答

2

在编写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) 
+0

由于这是伟大的,有助于想想这样。我可以真正厚颜无耻,并得到一个示例查询! – Bob 2011-05-21 18:22:34

+0

为什么不接受答案呢? – duffymo 2011-05-21 18:26:57

+0

它不会让我,我没有足够的代表:( – Bob 2011-05-21 18:33:55

0

您将需要两个表之间的三个表来保存数据对应关系。

Shelf_Cabinet Table 
ShelfID, CabinetID 

Item_Shelf Table 
ItemID, ShelfID 
+1

如果搁板和柜子,物品和搁板之间存在多对多的关系,这是真实的,但我不'我相信物理学会允许它。 – duffymo 2011-05-21 17:59:56