0

我已经看到了处理这个问题的其他问题,并且我知道 PostgreSQL 没有内置的 upsert,必须使用 2 种方法来完成。这是我使用 pg gem 在 Ruby 中使用的代码。

@db.exec_params("UPDATE crawled SET url = $1, timestamp = $2 WHERE url = $1",[url,DateTime.now])

@db.exec_params("INSERT INTO crawled (url, timestamp) VALUES ($1, $2) WHERE NOT EXISTS 
              (SELECT 1 FROM crawled WHERE url = $1)",[url,DateTime.now])

但是,当我运行它时,我得到一个语法错误

exec_params': ERROR:  syntax error at or near "WHERE" (PG::Error)
LINE 1: ...ERT INTO crawled (url, timestamp) VALUES ($1, $2) WHERE NOT ...

我的错误在哪里?

4

2 回答 2

0

仅从您的示例来看,我有两个问题。

  1. 哪一行导致错误?

  2. table应该用表名替换,不是吗?http://www.postgresql.org/docs/8.2/static/sql-insert.html

于 2013-07-24T10:41:21.400 回答
0

伪代码:

# transaction
query('BEGIN');

# find out if row already exists, and lock it if it does
result = query('SELECT * FROM crawled WHERE url = $1 FOR UPDATE', [url])

# row exists, so update it
if (result.rows > 0) {
    query('UPDATE crawled SET timestamp = $2 WHERE url = $1', [url, DateTime.now])
}

# row doesn't exist, insert
else {
    query('INSERT INTO crawled (url, timestamp) VALUES ($1, $2)', [url, DateTime.now])
}

# commit transaction
query('COMMIT');
于 2013-07-24T10:54:35.637 回答