我想要完成的是在pro
表中插入或更新数据并返回插入/更新的数据与关系。由于该表与另一个表有关系,我很难让它在一个查询中工作。我需要返回数据的原因是我需要使用 SQL 服务器上的最新数据相应地更新缓存。
create table profession
(
id serial primary key,
profession text NOT NULL
);
create table pro
(
id serial primary key,
profession int,
constraint fk_profession foreign key (profession) references profession (id)
);
create table users
(
id serial primary key,
pro_id int,
constraint fk_pro foreign key (pro_id) references pro (id)
);
INSERT INTO Profession (profession)
VALUES ('real_estate_agent'),
('real_estate_broker'),
('mortgage_broker'),
('property_inspector'),
('real_estate_attorney'),
('appraiser'),
('photographer'),
('interior_designer');
我在节点服务器上编写后端,并使用 pg-node 作为客户端。
let id;
// insert data if a relation doesn't exist. if not, does nothing
const { rows, rowCount } = await this.pool.query(`
INSERT INTO Pro (id, profession, created_at)
SELECT $1, $2, $3 from users
where id = $4 and pro_id is null
RETURNING *`, [pro.id, pro.profession, pro.created_at, uid]);
// get the name of a profession from the profession table from its id.
const mProfession = await this.pool.query('select profession from profession where id = $1', [profession])
// insert query won't insert if pro_id already exist on user
// so, i have to update the pro table
if (rowCount <= 0) {
// if 1st query didn't insert, update the table
const { rows } = await this.pool.query(`
update pro
set profession = $1
from users
where users.id = $2
and pro.id = users.pro_id
returning pro_id`, [pro.profession, uid]);
id = rows[0].pro_id
// update cache logic here
} else {
id = rows[0].id
// if insert is success, cache is updated here
}
return { id, profession: mProfession.rows[0].profession }
下面的代码按预期工作。我只想提高查询的性能和可读性。
预期回报是这样的:
{
id: 1,
profession: "real_estate_agent"
}
这可以在一个查询中完成吗?我找不到任何有助于在线完成此任务的内容。
信息:我在我的数据库中使用 uuid。这就是我插入 id 的原因。