如何检查记录是否存在然后返回1,否则在MySQL中返回0

时间:2013-10-07 15:58:37

标签: mysql sql

我有一个电话号码数据库。在这个数据库中我有一个名为“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

注意:我不想添加新的唯一索引,我不希望用户进行重复密钥更新。

2 个答案:

答案 0 :(得分:2)

通过对LEFT JOIN表执行contact_numbers并在将结果限制为NULL后查找main_number = 1,您可以在CASE中使用SELECT {1}}列表以相应地分配1或0.

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

答案 1 :(得分:0)

或者您可以使用 IF

SELECT ....
    IF(cn.number_id IS NULL, 1, 0) as main_number
FROM .....