postgresql 如何比较postgres中的两个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4814597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-20 00:31:09  来源:igfitidea点击:

How to compare two tables in postgres

postgresql

提问by jnivasreddy

I want compare two column values which come from two different queries. Can anyone suggest a query which compares two columns in Postgres?

我想比较来自两个不同查询的两个列值。谁能建议一个比较 Postgres 中两列的查询?

回答by Mike Sherrill 'Cat Recall'

Well, the easiest to understand--but not necessarily the fastest--is probably something like this. (But you might mean something else by "compare".)

嗯,最容易理解——但不一定是最快的——可能是这样的。(但“比较”可能是其他意思。)

-- Values in column1 that aren't in column2.
SELECT column1 FROM query1 
WHERE column1 NOT IN (SELECT column2 FROM query2);

-- Values in column2 that aren't in column1.
SELECT column2 FROM query2 
WHERE column2 NOT IN (SELECT column1 FROM query1);

-- Values common to both column1 and column2
SELECT q1.column1 FROM query1 q1
INNER JOIN query2 q2 ON (q1.column1 = q2.column2);

You can also do this in a single statement to give you a visual comparison. A FULL OUTER JOINreturns all the values in both columns, with matching values in the same row, and NULLwhere one column is missing a value that's in the other column.

您也可以在单个语句中执行此操作,以便进行视觉比较。AFULL OUTER JOIN返回两列中的所有值,在同一行中具有匹配值,并且NULL其中一列缺少另一列中的值。

SELECT q1.column1, q2.column2 FROM query1 q1
FULL OUTER JOIN query2 q2 ON (q1.column1 = q2.column2);