简体   繁体   English

如何组合两个查询还是只有一个?

[英]How do combine two Queries or is it only one?

Question:问题:

How do combine two Queries or is it only one?如何组合两个查询还是只有一个?

Example:例子:

I have two exact similar tables my PostgreSQL Database.我的 PostgreSQL 数据库有两个完全相同的表。 info_table and info_table_dump with the exact same columns date_at , name , color and length . info_tableinfo_table_dump具有完全相同的列date_atnamecolorlength Now i want to know if there are entries in info_table_dump that do not exist in info_table .现在我想知道 info_table_dump 中是否有info_table_dump中不存在的info_table Therefore i made these Query:因此我做了这些查询:

SELECT
date_at,name,color,length
FROM
info_table_dump
EXCEPT
SELECT
date_at,name,color,length
FROM
info_table;

The result is fine.结果很好。 It works like i assumed (i created 2 entries that do not match) the none-duplicates are shown.它就像我假设的那样工作(我创建了 2 个不匹配的条目)显示了非重复项。 But now i wanted only to fetch the given id s of the non-duplicate rows.但现在我只想获取非重复行的给定id Something like this...像这样的东西...

SELECT
id
FROM
info_table_dump
WHERE
(SELECT
date_at,name,color,length
FROM
info_table_dump
EXCEPT
SELECT
date_at,name,color,length
FROM
info_table);

I also tried something with EXISTS but its not the result i wanted.我也尝试了EXISTS的一些东西,但它不是我想要的结果。

So my Question how do combine the Query?所以我的问题如何结合查询?

I want only the ìd s of the info_table_dump rows, who not already exist in info_table .我只想要ìd行的info_table_dump ,它们在info_table中不存在。

So they should not exist in info_table?那么它们不应该存在于 info_table 中吗?

SELECT id
FROM info_table_dump d
WHERE NOT EXISTS (
  SELECT 1
  FROM info_table i
  WHERE i.date_at IS NOT DISTINCT FROM d.date_at
    AND i.name IS NOT DISTINCT FROM d.name
    AND i.color IS NOT DISTINCT FROM d.color
    AND i.length IS NOT DISTINCT FROM d.length
);

The IS NOT DISTINCT FROM is just in case some columns are nullable. IS NOT DISTINCT FROM只是以防某些列可以为空。

Test on db<>fiddle here这里测试 db<>fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM