我正在尝试编写一个查询来更新long a;
表的外键invoice_id。
schedule
但我收到错误代码:1093。您无法在FROM子句中为更新指定目标表'schedule'。还有其他方法可以根据month和company_id更新CREATE TABLE `invoices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_date` date NOT NULL,
`company_id` int(11) NOT NULL,
PRIMARY KEY (`id`))
CREATE TABLE `schedule` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`payment_date` date NOT NULL,
`company_id` int(11) NOT NULL,
`invoice_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `fk_company_id_idx` (`company_id`),
KEY `fk_schedule_invoices_idx` (`invoices_id`),
CONSTRAINT `fk_schedule_company` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
CONSTRAINT `fk_schedule_invoices` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
UPDATE schedule
SET invoice_id=(SELECT id FROM invoices ORDER BY id DESC LIMIT 1)
WHERE (company_id=1
AND (SELECT EXTRACT(MONTH FROM payment_date) as schedule_month FROM schedule WHERE company_id=1)=
(SELECT EXTRACT(MONTH FROM invoice_date) as invoice_month FROM invoices WHERE company_id=1))
吗?
修改
实际上我想要实现的是创建一个触发器,在插入新发票后更新invoice_id
表的invoice_id字段。该更新应基于company_id,年份和月份(同月的天数不同)。我只是尝试在不创建触发器的情况下进行更新
答案 0 :(得分:0)
正如我在帖子编辑中提到的,我需要设置schedule.invoice_id值。我是SQL的新手,所以我最初写错了一个条件。感谢@Michael Berkowski提示
UPDATE schedule s
JOIN invoices i
ON s.company_id=i.company_id
SET s.invoice_id=i.id
WHERE month(s.payment_date)=month(i.invoice_date)