简体   繁体   English

PostgreSQL 检查值是否存在于另一个表中

[英]PostgreSQL check if value exists in another table

I'm trying to find a solution in PostgreSQL of how I can add to the output of the query extra column with value if id exists in another table or not:我试图在 PostgreSQL 中找到一个解决方案,如果 id 是否存在于另一个表中,我如何将其添加到查询额外列的 output 中:

I need several things:我需要几样东西:

  1. Do a join between two tables在两个表之间进行连接
  2. Add a new column into the result output where I check if exists in the third table or not在结果 output 中添加一个新列,我检查第三个表中是否存在

My tables:我的桌子:

  • announcement公告
  • author作者
  • chapter章节

announcement table announcement

| id | author_id | date | group_id |... |

author table author

| id | name | email |... |

chapter table chapter

| id | announcement_id |... |

This is what I have now.这就是我现在所拥有的。 I did a left outer join and it works as I expected:我做了一个左外连接,它按我的预期工作:

select announcement.id, announcement.date, author.id as publisher_id, author.name as publisher_name
from announcement 
left outer join author 
on announcement.author_id = author.id
where announcement.group_id = 123 and announcement.date >= '2022-06-01'::date;

with output:与 output:

| id | date       | publisher_id | publisher_name |
| 1  | 2020-07-01 | 12           | John           |
| 2  | 2020-07-04 | 123          | Arthur         |

Now I can't find a solution of how to add an extra column with_chapters to the query response, where I will check if announcement.id exists in chapter table under announcement_id column .现在我找不到如何在查询响应中添加额外的列with_chapters的解决方案,我将在其中检查if announcement.id exists in chapter table under announcement_id column

For example, chapter table can have such data:例如,章节表可以有这样的数据:

| id | announcement_id |
| 1  | 1               |
| 2  | 1               |
| 3  | 1               |

So we see that some announcements can appear in chapters several times (so i'm looking for at least 1 match).所以我们看到一些公告可以多次出现在章节中(所以我正在寻找至少 1 个匹配项)。 And some announcements doesn't have chapters at all.有些公告根本没有章节。

Output finally should be like that: Output 最后应该是这样的:

| id | date       | publisher_id | publisher_name | with_chapters |
| 1  | 2020-07-01 | 12           | John           | true          |
| 2  | 2020-07-04 | 123          | Arthur         | false         |

Thanks a lot for any help:)非常感谢您的帮助:)

While EXISTS (subquery) is usually used in the WHERE clause, it returns an ordinary Boolean and so can be used in the select list.虽然EXISTS (subquery)通常用于 WHERE 子句,但它返回一个普通的 Boolean,因此可以在 select 列表中使用。

SELECT blah1, blah2, 
       EXISTS (select 1 from chapter where chapter.announcement_id=announcement.id) as with_chapter
FROM ...

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

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