1

我有一个电话号码数据库。在这个数据库中,我有一个名为“main_number”的列,它是一个 tinyint(1) 类型,我使用 0 表示非主编号或 1 表示主编号。

我遇到的问题是我使用存储过程从一个数据库批量插入到另一个数据库。

业务规则规定,只有一个电话号码可以标记为主电话号码。现在,我需要做的是检查是否已经有一条标记为“main_number”的记录,如果是,那么“main_number”的值应该是 0。但是如果没有找到记录,那么我应该让 main_number = 1。

以下是我的表的辩护

CREATE TABLE `contact_numbers` (
 `number_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `account_id` int(10) unsigned DEFAULT NULL,
 `person_id` int(11) DEFAULT NULL,
 `contact_number` char(15) NOT NULL,
 `contact_extension` char(10) DEFAULT NULL,
 `contact_type` enum('Office','Fax','Reception','Direct','Cell','Toll Free','Home') NOT NULL DEFAULT 'Office',
 `contact_link` enum('Account','PDM','Other') NOT NULL DEFAULT 'Account',
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0 = inactive, 1=active',
 `main_number` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 = main phone number',
 `created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `created_by` int(11) NOT NULL,
 `modified_on` datetime DEFAULT NULL,
 `modified_by` int(11) NOT NULL DEFAULT '0',
 `external_id1` char(18) DEFAULT NULL COMMENT 'client''s account id',
 `external_id2` char(18) DEFAULT NULL COMMENT 'client''s person id',
 PRIMARY KEY (`number_id`),
 UNIQUE KEY `external_id1` (`external_id1`),
 UNIQUE KEY `external_id2` (`external_id2`),
 UNIQUE KEY `person_id_2` (`person_id`,`contact_type`),
 UNIQUE KEY `person_id_3` (`person_id`,`contact_number`,`contact_extension`),
 UNIQUE KEY `account_id_4` (`account_id`,`contact_number`,`contact_extension`),
 KEY `account_id` (`account_id`),
 KEY `person_id` (`person_id`),
 KEY `account_id_2` (`account_id`,`contact_link`,`main_number`),
 CONSTRAINT `cn_account_id` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`account_id`) ON DELETE CASCADE ON UPDATE CASCADE,
 CONSTRAINT `cn_person_id` FOREIGN KEY (`person_id`) REFERENCES `contact_personal` (`person_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=114851 DEFAULT CHARSET=utf8

这是我的查询,我需要添加检查以查看是否存在 account_id 的 main_number = 1 的记录。

SELECT ac.account_id, a.phone, 'Office', 'Account', 1 AS created_by
FROM rdi_ge_dev.account AS a
INNER JOIN finaltesting.accounts AS ac ON ac.external_id1 = a.SFDC_account_id

注意:我不想添加新的唯一索引,也不想使用重复键更新。

4

2 回答 2

2

通过LEFT JOIN对表执行 a 并在将其结果限制contact_numbers为之后查找 a ,您可以在列表中使用 a 来相应地分配 1 或 0。NULLmain_number = 1CASESELECT

SELECT
  ac.account_id,
  a.phone,
  'Office',
  'Account',
  1 AS created_by,
  /* A null in the LEFT JOIN means it doesn't already exist */
  CASE WHEN cn.number_id IS NULL THEN 1 ELSE 0 END AS main_number
FROM
  rdi_ge_dev.account AS a
  INNER JOIN finaltesting.accounts AS ac ON ac.external_id1 = a.SFDC_account_id
  LEFT JOIN contact_numbers AS cn ON a.account_id = cn.account_id
WHERE 
  /* Limit the left join to only main_number = 1 */
  cn.main_number = 1
于 2013-10-07T16:06:45.787 回答
0

或者您可以使用IF

SELECT ....
    IF(cn.number_id IS NULL, 1, 0) as main_number
FROM .....
于 2021-05-10T11:44:25.777 回答