使用 H2,我想尝试更新一行。如果它不存在,我想插入它。 如果可能的话,我想在一个 SQL 语句中完成所有操作,以避免并发问题。
到目前为止,我有更新:
UPDATE RATING
SET NUM_RATINGS = (SELECT NUM_RATINGS + 1 FROM RATING WHERE EVENT_UID = :eventUid)
, SUM_RATINGS = (SELECT SUM_RATINGS + :newRating FROM RATING WHERE EVENT_UID = :eventUid)
WHERE EVENT_UID = :eventUid AND EXISTS ( SELECT * FROM RATING WHERE EVENT_UID = :eventUid)
表定义为:
CREATE TABLE RATING (
ID BIGINT NOT NULL,
EVENT_UID VARCHAR(255) NOT NULL,
SUM_RATINGS BIGINT NOT NULL,
NUM_RATINGS INT NOT NULL,
PRIMARY KEY (ID),
FOREIGN KEY (EVENT_UID) REFERENCES EVENT(UID)
)
任何人都可以改进更新声明吗?
如果该行不存在,我如何在同一个 SQL 语句中添加如下所示的插入?
INSERT INTO RATING ( ID , EVENT_UID , NUM_RATINGS , SUM_RATINGS )
VALUES (2, 'BWEIY-A4', 1, 4)