Postgresql 左连接到默认值表
我有一个每天都需要运行的进程列表,如果成功或失败,在运行写入DB之后, 以下是表格:Postgresql 左连接到默认值表,postgresql,Postgresql,我有一个每天都需要运行的进程列表,如果成功或失败,在运行写入DB之后, 以下是表格: CREATE TABLE process(name text, status text, reason text); INSERT INTO process VALUES ('run','OK',''), ('stop','ERROR','exception'); 我还有一个表,其中列出了需要运行的所有进程 CREATE TABLE full_process
CREATE TABLE
process(name text, status text, reason text);
INSERT INTO
process
VALUES
('run','OK',''),
('stop','ERROR','exception');
我还有一个表,其中列出了需要运行的所有进程
CREATE TABLE
full_process(name text, status text, reason text);
INSERT INTO
full_process
VALUES
('run','ERROR','script didnt run'),
('stop','ERROR','script didnt run'),
('report','ERROR','script didnt run');
我想左键连接它们,这样我就可以从process
表中获取所有运行的进程,并从full\u process
表中获取未运行的进程的默认值
我试过这个
SELECT
a.*,
b.*
FROM
process as a
LEFT JOIN full_process as b ON a.name = b.name;
但是我只从
full\u process
表中获取默认值,而当我尝试相反的方法时,我只从process
表中获取默认值,您可能正在查找以下内容:
SELECT
a.*,
b.*
FROM
process as a
FULL OUTER JOIN full_process as b ON a.name = b.name;
因此,解决方案是:
SELECT a.name, b.status,
b.reason
FROM full_process as a
LEFT JOIN process as b
ON a.name = b.name
如果我不希望表中有null
SELECT a.name,
COALESCE(b.status, 'ERROR') AS statusת
COALESCE(b.reason, 'RECORD MISSING') AS reason
FROM full_process as a
LEFT JOIN process as b
ON a.name = b.name
您使用的是什么ORM或数据库库?请注意,结果包含多个同名列,这可能不是最佳结果。尝试选择
b.status作为默认\u status
或类似的内容。不,我正在寻找左连接,我想要process
中的所有行以及process
中不包含的内容从full\u process
中获取注意,这将为NULL
提供默认值,而不是process
表中不包含的行的默认值。我知道,我有这样的理由。我会更新我的答案。您可以将其简化为合并(b.reason,'recordmissing')作为原因btw@Bergi我不知道这个函数,它更干净(tnx:)