如果你提供了一个数据库结构的例子,这将是有益的。此外,您应该首先通过为国家,配方和配料创建单独的表格来优化数据库。就像现在一样,您只需列出所有成分,就可以在同一国家和地区重复输入。
你的表应该是这样的:
国家表
countryId countryName
1 United States of America
2 England
食谱表
recipeId recipeName countryId dateAdded
1 Jambalaya 1 2012-10-11
2 Bangers and Mash 2 2013-11-04
成分
ingredientId ingredientName
1 rice
2 potato
配方和配料地图
riMapId recipeId ingredientId
1 1 1
2 2 2
成分和配方的“配方和配料地图”表关联。这将国家与成分恰当地分开,并允许您有更多的领域,如'dateAdded',与成分或国家无关。虽然这使得select语句更加复杂,但它也使得它们更加高效和强大。
要选择所有的成分从两国
SELECT
`ingredients`.`ingredientName` AS 'ingredientName',
`countries`.`countryName` AS 'countryName',
`recipes`.`recipeName` AS 'recipeName',
`recipeIngredientMap`.`riMapId` AS 'riMapId'
FROM
`ingredients`
LEFT JOIN
`recipeIngredientMap` ON `recipeIngredientMap`.`ingredientId` = `ingredients`.`ingredientId`
LEFT JOIN
`recipes` ON `recipes`.`recipeId` = `recipeIngredientMap`.`recipeId`
JOIN
`countries` ON `countries`.`countryId` = `recipes`.`countryId` AND
`countries`.`countryId` IN (1,2)
从相同的两个国家选择配方的次数
SELECT
COUNT(`recipeName`) AS 'recipeCount'
FROM
`recipes`
WHERE
`countryId` IN (1,2)
MYSQL结构
--
-- Database: `food`
--
-- --------------------------------------------------------
--
-- Table structure for table `countries`
--
CREATE TABLE `countries` (
`countryId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`countryName` varchar(255) NOT NULL,
PRIMARY KEY (`countryId`),
UNIQUE KEY `countryName` (`countryName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
-- --------------------------------------------------------
--
-- Table structure for table `ingredients`
--
CREATE TABLE `ingredients` (
`ingredientId` int(11) NOT NULL AUTO_INCREMENT,
`ingredientName` varchar(255) NOT NULL,
PRIMARY KEY (`ingredientId`),
UNIQUE KEY `ingredientName` (`ingredientName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
-- --------------------------------------------------------
--
-- Table structure for table `recipeIngredientMap`
--
CREATE TABLE `recipeIngredientMap` (
`riMapId` int(11) NOT NULL AUTO_INCREMENT,
`recipeId` int(10) unsigned NOT NULL,
`ingredientId` int(10) unsigned NOT NULL,
PRIMARY KEY (`riMapId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
-- --------------------------------------------------------
--
-- Table structure for table `recipes`
--
CREATE TABLE `recipes` (
`recipeId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`recipeName` varchar(255) NOT NULL,
`countryId` int(10) unsigned NOT NULL,
`dateAdded` date NOT NULL,
PRIMARY KEY (`recipeId`),
UNIQUE KEY `recipeName` (`recipeName`),
KEY `countryId` (`countryId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
请注意,许多字段都设置为唯一索引。这可以防止重复信息。我会更进一步并添加外键,以防止插入引用不存在的项目的行。
表的结构只是三列(国家,食谱,成分)。所有这些都是主键。所以你可以有多个国家/配方同名,但没有国家/配方/配料可以相同。 – Eric 2011-04-18 00:39:57