你需要这样的东西(简化版只包含必填字段):
数据库结构:
CREATE TABLE IF NOT EXISTS `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_name` varchar(50) NOT NULL,
`required_quantity` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `items` (`id`, `item_name`, `required_quantity`) VALUES
(1, 'Item 1', 10),
(2, 'Item 2', 20);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `locations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`location_name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Zrzut danych tabeli `locations`
--
INSERT INTO `locations` (`id`, `location_name`) VALUES
(1, 'Location 1'),
(2, 'Location 2');
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `locations_items` (
`location_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`actual_quantity` int(11) NOT NULL,
UNIQUE KEY `location_id` (`location_id`,`item_id`),
KEY `item_id` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `locations_items` (`location_id`, `item_id`, `actual_quantity`) VALUES
(1, 1, 5),
(2, 2, 7);
ALTER TABLE `locations_items`
ADD CONSTRAINT `locations_items_ibfk_1` FOREIGN KEY (`location_id`) REFERENCES `locations` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `locations_items_ibfk_2` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON UPDATE CASCADE;
查询以获取每个位置和每个位置所需(基本数量)和实际数量的每个项目:
SELECT
q.location_id,
q.location_name,
q.item_id,
q.item_name,
q.required_quantity,
IFNULL(li.actual_quantity, 0) AS actual_quantity
FROM
(SELECT
l.id AS location_id,
l.location_name,
i.id AS item_id,
i.item_name,
i.required_quantity
FROM
locations AS l
CROSS JOIN items AS i
) AS q
LEFT JOIN locations_items AS li ON q.location_id = li.location_id AND q.item_id = li.item_id
SQL Fiddle Demo
您在表items 中有常用项目列表,您可以在其中输入所有位置所需的标准数量。如果您需要更新它,请在同一张表中进行,它会立即应用于所有位置。
在表locations_items 中插入/更新实际位置,每个位置和项目都是唯一的。在那里您可以记录每个位置的实际数量。
查询可让您在所有位置获取所有需要/实际数量的项目。您当然可以使用附加条件对其进行微调以获得特定位置或项目。