如果你提供了一個數據庫結構的例子,這將是有益的。此外,您應該首先通過爲國家,配方和配料創建單獨的表格來優化數據庫。就像現在一樣,您只需列出所有成分,就可以在同一國家和地區重複輸入。
你的表應該是這樣的:
國家表
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