将表A与表B进行比较在INSERT数据A INTO B之前

时间:2017-06-09 09:49:57

标签: mysql

我有以下2个表:

A) inventory
(`id`, `item`, `qty_left`, `qty_min`, `qty_max`, `cat_no`, `supplier`) VALUES
(1, 'Orange', 6, 10, 50, 1001, 'ACOMP'),
(2, 'Apple', 4, 10, 20, 1002, 'BCOMP'),
(3, 'Pear', 80, 20, 100, 1003, 'ACOMP'),
(4, 'Durian', 90, 60, 100, 1004, 'CCOMP');

B) reorder_in_process (`id`, `item`, `to_order`, `cat_no`, `supplier`) VALUES
(Empty)

如果我在下面运行查询,(使用PHP,SQL和JS)将项目置于低数量到表B,

(Say q = BCOMP)
SELECT * FROM inventory WHERE qty_left<=qty_min AND supplier='$q'
$to_order = $qty_max -$qty_left;
INSERT INTO reorder_in_process VALUES (NULL, '$item', '$to_order', '$cat_no', '$q')";

表B将是这样的:

reorder_in_process (`id`, `item`, `to_order`, `cat_no`, `supplier`) VALUES
(72, 'Apple', 16, 1002, 'BCOMP');

现在的问题是,如果我再次运行上述查询,

表B将是这样的:

reorder_in_process (`id`, `item`, `to_order`, `cat_no`, `supplier`) VALUES
(72, 'Apple', 16, 1002, 'BCOMP');
(73, 'Apple', 16, 1002, 'BCOMP');

我不希望这种情况发生。那么,我该怎么办?

1) if row containing(cat_no ='1002') already exist in table B, new INSERT of
 (cat_no='1002') will not be allowed/happened,
2) if row containing(cat_no) that not exist in table B, new INSERT is allowed.

请建议。感谢。

1 个答案:

答案 0 :(得分:1)

在表B的cat_no列上添加一个唯一索引,然后改为INSERT IGNORE