我正在考虑做一些类似的事情...
Table Pants (20 entrees)
| ID | Item | Description | Price
Table Shirts (20 entrees)
| ID | Item | Description | Price
Table Socks (5 entrees)
| ID | Item | Description | Price
然后我在 $table 中运行 php foreach ID,以填充页面上的列表。
既然我的一些 table 可能没有很多主菜,那么这是一种有效的方法吗?或者我应该将所有主菜放在一个表中,并为不同的类别添加一个额外的字段,并找到另一种通过新字段填充我的页面的方法?或者也许是一个更好的主意?
感谢您的宝贵时间。
最佳答案
您的模型不灵活且效率不高。您的第二个解决方案是好的解决方案,创建一个名为 items 的表并添加一个名为categories 的额外字段,该字段应该是外键。 你可以检查这个http://sqlfiddle.com/#!2/74c91/1 ,这就是您所需要的 这是创建数据库所需的代码:
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;
-- Dumping structure for table database.categories
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table database.categories: ~0 rows (approximately)
/*!40000 ALTER TABLE `categories` DISABLE KEYS */;
INSERT INTO `categories` (`id`, `name`, `created`) VALUES
(1, 'Pants ', '2012-12-15 11:37:27'),
(2, 'Shirts ', '2012-12-15 11:37:36'),
(3, 'Socks ', '2012-12-15 10:38:47');
/*!40000 ALTER TABLE `categories` ENABLE KEYS */;
-- Dumping structure for table database.clothes
CREATE TABLE IF NOT EXISTS `clothes` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`item` varchar(255) NOT NULL,
`description` text,
`category_id` int(10) NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `category_id` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table database.clothes: ~0 rows (approximately)
/*!40000 ALTER TABLE `clothes` DISABLE KEYS */;
INSERT INTO `clothes` (`id`, `item`, `description`, `category_id`, `created`) VALUES
(1, 'red socks', 'Red Socks Rocks', 3, '2012-12-15 10:39:06'),
(2, 'blue socks', 'nice socks too', 3, '2012-12-15 10:39:18'),
(3, 'grey pants', 'pretty cool', 1, '2012-12-15 10:40:34'),
(4, 'Blue Shirt', 'Nice blue shirt', 2, '2012-12-15 10:40:10');
/*!40000 ALTER TABLE `clothes` ENABLE KEYS */;
/*!40014 SET FOREIGN_KEY_CHECKS=1 */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
这是检索数据的代码:
SELECT
clothes.id AS clotheId,
clothes.item AS clotheItem,
clothes.description AS clotheDescription,
categories.id AS categoryId,
categories.name AS categoryName
FROM clothes
LEFT JOIN categories
ON clothes.category_id=categories.id;
关于mysql - 创建 MySQL 数据库最有效的方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893396/