我正在尝试使用带有 pg 扩展名(版本 0.5.4)的 node.js 在 postgres 数据库中进行插入或更新。
到目前为止,我有这个代码:(...)
client.query({
text: "update users set is_active = 0, ip = $1 where id=$2",
values: [ip,id]
}, function(u_err, u_result){
debug(socket_id,"update query result: ",u_result);
debug(socket_id,"update query error: ",u_err);
date_now = new Date();
var month = date_now.getMonth() + 1;
if(!u_err){
client.query({
text: 'insert into users (id,first_name,last_name,is_active,ip,date_joined) values' +
'($1,$2,$3,$4,$5,$6)',
values: [
result.id,
result.first_name,
result.last_name,
1,
ip,
date_now.getFullYear() + "-" + month + "-" + date_now.getDate() + " " + date_now.getHours() + ":" + date_now.getMinutes() …Run Code Online (Sandbox Code Playgroud) 我在postgresql中使用下面的命令创建一个表.
CREATE TABLE someTable (
id serial primary key,
col1 int NOT NULL,
col2 int NOT NULL,
unique (col1, col2)
);
Run Code Online (Sandbox Code Playgroud)
然后我执行2个插入语句.
insert into someTable (col1,col2) values(1,11),(1,12);
它的工作
insert into someTable (col1,col2) values(1,13),(1,14),(1,11);
得到错误(key(col1,col2)=(1,11)已经存在.
但我需要避免重复对.怎么可能?
我试试这个
x86_64-pc-linux-gnu上的PostgreSQL 9.5.0,由gcc编译的gcc(Ubuntu 4.8.2-19ubuntu1)4.8.2,64位和PostgreSQL 9.3,由gcc编译(Ubuntu 4.8. 2-19ubuntu1)4.8.2,64位
但我得到了错误
执行两个语句后我需要这样做.
(1,11),(1,12),(1,13),(1,14)
Run Code Online (Sandbox Code Playgroud) 表定义是
create table users (
serial_no integer PRIMARY KEY DEFAULT nextval('serial'),
uid bigint NOT NULL,
username varchar(32),
name text,
CONSTRAINT production UNIQUE(uid)
);
Run Code Online (Sandbox Code Playgroud)
我用过这个查询
INSERT INTO users (uid) values(123) ;
Run Code Online (Sandbox Code Playgroud)
它表示重复键值违反了唯一约束.所以我用Google搜索并发现了这个链接
所以我试过了
INSERT INTO users (uid) values(123)
where 1 in (select 1 from users where uid = 123) ;
Run Code Online (Sandbox Code Playgroud)
它在"WHERE"或附近说yntax错误.
如何使用insert子句来使用where子句,这样当我使用php运行相同的查询时,它不会返回错误
列uid是独一无二的
我按以下方式使用psycopg2插入项目:
cursor = connection.cursor()
for item in items:
try:
cursor.execute(
"INSERT INTO items (name, description) VALUES (%s, %s) RETURNING id",
(item[0], item[1])
)
id = cursor.fetchone[0]
if id is not None:
cursor.execute(
"INSERT INTO item_tags (item, tag) VALUES (%s, %s) RETURNING id",
(id, 'some_tag')
)
except psycopg2.Error:
connection.rollback()
print("PostgreSQL Error: " + e.diag.message_primary)
continue
print(item[0])
connection.commit()
Run Code Online (Sandbox Code Playgroud)
显然,当一个项目已经在数据库中时,duplicate key exception就会抛出该项目.有没有办法忽略这个例外?抛出异常时是否会中止整个事务?如果是,那么重写查询的最佳选择是什么,可能使用批量插入?
我需要UPSERTPostgres的功能.由于Postgres本身不支持这个,我编写了一个函数来执行该操作(尝试更新,如果没有更新行则插入)
这是该功能的模板:https://stackoverflow.com/a/1109198/681671
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过更新或在vote_user_table中插入新记录来更新数据库.该表定义如下:
Column | Type | Modifiers
-----------+---------+--------------------------------------------------------------
id | integer | not null default nextval('vote_user_table_id_seq'::regclass)
review_id | integer | not null
user_id | integer | not null
positive | boolean | default false
negative | boolean | default false
Indexes:
"vote_user_table_pkey" PRIMARY KEY, btree (id)
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的查询.我实际上正在为所有值使用参数,但出于测试目的,我将它们替换为我确定应该工作的值.用户名aaa@aaa.com存在.
WITH updated AS (
UPDATE vote_user_table
SET
positive = 'true',
negative = 'false'
FROM usuario
WHERE
review_id = 6 AND
user_id = usuario.id AND
usuario.username ILIKE 'aaa@aaa.com'
RETURNING vote_user_table.id
) …Run Code Online (Sandbox Code Playgroud) sql postgresql upsert common-table-expression postgresql-9.2
如果现在重要的是我正在使用MySQL/MyISAM,但我愿意使用PostgreSQL.我也愿意使用memcached.
考虑一个用于存储论坛帖子的表格:
id forum_name post_date
1 Hey! 2009-01-01 12:00:00
Run Code Online (Sandbox Code Playgroud)
我是不是该..
创建一个单独的表,如
id thread_id views
1 1 532
Run Code Online (Sandbox Code Playgroud)
或者将它保存为初始线程表中的列?
id forum_name post_date views
1 Hey! 2009-01-01 12:00:00 532
Run Code Online (Sandbox Code Playgroud)
另一个相关的小窍门,显示和增加页面浏览量的实用解决方案是什么?我读了这个帖子,似乎我只能缓存一段时间的值,我对增量部分并不十分清楚 - 也许就像将值存储在某个地方的平面文件中,然后定期用cronjobs更新数据库论坛视图每小时左右?
编辑: 澄清一下,投票就像SO一样,每个帖子一票,并且可以有逆转.没关系我对柜台的意思.
我正在使用一个postgreSQL数据库,它有一个"公司"表和一个"国家"表,每个表都有一个唯一ID.
我想要一个设置,如果我尝试将公司添加到数据库,它只会将公司添加到具有新唯一ID的数据库(如果它尚不存在).
如果有人能够对此有所了解,我会非常感激,
詹姆士
输入以下命令时:
\copy mmcompany from '<path>/mmcompany.txt' delimiter ',' csv;
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
ERROR: duplicate key value violates unique constraint "mmcompany_phonenumber_key"
Run Code Online (Sandbox Code Playgroud)
我理解为什么会这样,但是如何以插入有效条目的方式执行命令,并且会丢弃创建错误的命令?
您好我有一个简单的表:
+------------+------------+----------------------+----------------+
|id (serial) | date(date) | customer_fk(integer) | value(integer) |
+------------+------------+----------------------+----------------+
Run Code Online (Sandbox Code Playgroud)
我想像每日累加器一样使用每一行,如果客户价值到达,如果不存在该客户和日期的记录,则为该客户和日期创建一个新行,但如果存在则仅增加该值.
我不知道如何实现这样的东西,我只知道如何使用SET增加一个值,但这里需要更多的逻辑.提前致谢.
我使用的是9.4版
postgresql ×8
sql ×7
upsert ×2
commit ×1
database ×1
java ×1
jdbc ×1
mysql ×1
node.js ×1
pg ×1
psycopg2 ×1
python ×1
spring-jdbc ×1
sql-insert ×1