首页 > 解决方案 > 使用从另一个表中随机选取的唯一值更新表中的列

问题描述

扩展我之前的问题以限制它更新重复值。


我有一个带有列的table1

重新定义 公司编号 地址ID
xyz 230 无效的
yzf 239 无效的

我有另一个带有列的表table2

地址编号 公司
11223344 231
11223345 230
11223354 239
11223334 239

我想从 Table2 中随机获取一个唯一 ID 并更新 table1 中公司编号 = 公司地址 ID 为空的列地址 ID?

另外,我每天都会在 table1 中添加新行,如何限制重复的地址 ID 从 table2 中获取?

标签: sqloracle

解决方案


您可以通过创建用于在 table1 上插入的触发器来做到这一点。然后从 table2 中选择所有尚未在 table1 中设置的 AddressId,随机排序并选择第一个。这种触发器的一个工作示例:

CREATE TRIGGER TRIGGER1 
BEFORE INSERT ON TABLE1 
FOR EACH ROW /* Trigger for each new row inserted into table1 */
BEGIN
SELECT addressId INTO :new.ADDRESSID /* Set AddressId for new row in table1 */ FROM 
(
   SELECT table2.addressId FROM table2
   LEFT JOIN table1 ON table1.CompanyNumber = table2.company AND table1.AddressID = table2.addressId
   WHERE table1.AddressID IS NULL /* Not already in table1 */ AND table2.Company = :new.COMPANYNUMBER /* Select all addressIds matching the company number */
   ORDER BY dbms_random.value /* order them randomly */
 ) hits
 WHERE ROWNUM = 1; /*Only pick the first randomly ordered one*/
    
EXCEPTION
  WHEN no_data_found THEN /* CompanyNumber not in table2 or no unique AddressId left */
     :new.ADDRESSID := NULL;
END;

推荐阅读