PostgreSQL如何从一个表中选择仅在另一表中可用的列中的值? [英] Postgresql how to select values in the column from one table that are only available in another table?

查看:69
本文介绍了PostgreSQL如何从一个表中选择仅在另一表中可用的列中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Postgresql,需要查询两个表,如下所示:

I am using Postgresql and need to query two tables like this:

Table1

  ID     Bill  
  A       1
  B       2
  B       3
  C       4

表2

 ID  
  A     
  B

我想要一个表,其中包含表1中的所有列,但仅保留具有表2中可用ID的记录(A和B)。另外,Table2的ID是唯一的。

I want a table with all the columns in Table1 but keeping only the records with IDs that are available in Table2 (A and B in this case). Also, Table2's ID is unique.

  ID     Bill  
  A       1
  B       2
  B       3

我应该使用哪个连接,或者是否可以使用WHERE语句?

Which join I should use or if I can use WHERE statement?

谢谢!

推荐答案

SELECT Table1.*
FROM Table1
  INNER JOIN Table2 USING (ID); 

SELECT * 
FROM Table1
WHERE ID IN (SELECT ID FROM Table2);

但第一个由于性能原因更好。

but the first one is better for performance reason.

这篇关于PostgreSQL如何从一个表中选择仅在另一表中可用的列中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆