我正在尝试编写一个过程,通过添加外键列来更新表,但返回错误。怎么了?
DROP PROCEDURE IF EXISTS tbl_file_add_column_instance_id;
DELIMITER //
CREATE PROCEDURE tbl_file_add_column_instance_id()
BEGIN
IF NOT EXISTS((SELECT column_name FROM information_schema.columns
WHERE table_name = 'tbl_file' AND table_schema = 'diginet2' AND column_name = 'instance_id'))
THEN
ALTER TABLE tbl_file ADD COLUMN instance_id INT NOT NULL AFTER id;
ALTER TABLE tbl_file ADD CONSTRAINT id_instance_arq FOREIGN KEY (`instance_id`) REFERENCES `diginet2`.`tbl_instance` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Set rows that already exist
SET @query_initial_instance := (SELECT @initial_instance:=id FROM diginet.tbl_instance WHERE instance_status = 1 LIMIT 1);
IF COUNT(@query_initial_instance) = 1
THEN
UPDATE tbl_file SET instance_id = @initial_instance;
ELSE
-- fake throw error
SELECT * FROM diginet_has_none_or_more_than_one_instance;
END IF;
END IF;
END //
DELIMITER ;
CALL tbl_file_add_column_instance_id();
并且我收到此错误:错误代码1111。组功能的无效使用
答案 0 :(得分:0)
如果您想知道有多少行符合WHERE
条件,则应在查询中使用COUNT()
,而不要使用IF
语句。
SET @row_count = (SELECT COUNT(*) FROM diginet.tbl_instance WHERE instance_status = 1)
IF @row_count = 1
THEN
UPDATE tbl_file SET instance_id = (SELECT id FROM digitnet.tbl_instance WHERE intance_status = 1);
ELSE
-- fake throw error
SELECT * FROM diginet_has_none_or_more_than_one_instance;
END IF
我认为没有合法的方法可以在单个查询中获得计数和唯一值。您可以这样做:
SELECT @row_count := COUNT(*), @initial_instance:=id FROM diginet.tbl_instance WHERE instance_status = 1;
但这违反了ONLY_FULL_GROUP_BY
规则。