[英]ORACLE SQL UPDATE with INNER JOIN isn't working
I'm currently learning SQL, and I'm using ORACLE DATABASE.我目前正在学习 SQL,我正在使用 ORACLE DATABASE。 I've done the exercises of this website : https://sql.sh/exercices-sql/commandes and I'm doing the exact same things but for Oracle Database this time.
我已经完成了这个网站的练习: https : //sql.sh/exercices-sql/commandes ,我正在做完全相同的事情,但这次是针对 Oracle 数据库。
My problem is the following :我的问题如下:
I have these two tables :我有这两个表:
CREATE TABLE orders(
order_id INT GENERATED BY DEFAULT AS IDENTITY,
customer_id INT NOT NULL,
order_date DATE NOT NULL,
reference VARCHAR(255) NOT NULL,
total_price_cache DECIMAL(10, 3) NOT NULL,
PRIMARY KEY(order_id)
);
CREATE TABLE order_lines(
order_line_id INT GENERATED BY DEFAULT AS IDENTITY,
order_id INT NOT NULL,
name VARCHAR(255) NOT NULL,
quantity INT NOT NULL,
unit_price DECIMAL(10, 3) NOT NULL,
total_price DECIMAL(10, 3) NOT NULL,
PRIMARY KEY(order_line_id)
);
And I'm trying to do the following :我正在尝试执行以下操作:
UPDATE orders AS t1
INNER JOIN
( SELECT order_id, SUM(order_lines.total_price) AS p_total
FROM order_lines
GROUP BY order_id ) t2
ON t1.order_id = t2.order_id
SET t1.total_price_cache = t2.p_total
I works for MySQL but doesn't for Oracle Database.我适用于 MySQL,但不适用于 Oracle 数据库。 I keep getting the error ORA-00971 saying that the keyword SET is absent.
我不断收到错误 ORA-00971,说缺少关键字 SET。
Can someone explain me how to do this for Oracle database.有人可以向我解释如何为 Oracle 数据库执行此操作。
Thanks谢谢
Oracle does not support this MySQL-style update join syntax. Oracle 不支持这种 MySQL 风格的更新连接语法。 But, you may use a correlated subquery instead:
但是,您可以改用相关子查询:
UPDATE orders AS o
SET total_price_cache = (SELECT SUM(total_price) FROM order_lines ol
WHERE ol.order_id = o.order_id);
As an alternative to the update command, you can use merge
instead作为更新命令的替代方法,您可以使用
merge
代替
merge into orders target
using
( SELECT t2.order_id , SUM(t2.total_price) AS p_total
FROM order_lines t2 inner join orders t1
ON t1.order_id = t2.order_id
GROUP BY t2.order_id ) source
on ( target.order_id = source.order_id )
when matched then
update set target.total_price_cache = source.p_total
You can convert the MYSQL update with join into key preversed view in Oracle您可以使用 join 将 MYSQL 更新转换为 Oracle 中的关键保留视图
UPDATE (SELECT t1.total_price_cache AS total_price_cache,
t1.order_id,
t2.order_id
orders AS t1 ,
t2.p_total
FROM orders AS t1
INNER JOIN
( SELECT order_id, SUM(order_lines.total_price) AS p_total
FROM order_lines
GROUP BY order_id ) t2
ON t1.order_id = t2.order_id )
SET t1.total_price_cache = t2.p_total
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.