sql - 来自不同表的条件连接

标签 sql postgresql

我有一张看起来像 项目:

id   index
1     45
1     50
2     25
2     45

我正在写一个查询 从 items 中选择所有行。我需要用它的描述替换索引。 id 1表示table_a,id 2表示table_b。

表_A

index   description
45          'ddd'
50          'fff'

表_B

index   description
25          'AAA'
45          'BBB'

意味着我需要加入索引但取决于 id。

类似于:

Select id,index,description
from items
join table_A,table_B using (index)

我想得到的是:

id index description

1    45    'ddd'
1    50    'fff'
2    25    'AAA'
2    45    'BBB'

如何使用 1 Join 做到这一点?

最佳答案

您必须先 UNION Table_A 和 Table_B,然后按如下方式加入 Items

Select id,index,T.description from items
join (select 1 as id, index, description from Table_A 
UNION select 2 as id, index, description from Table_B) as T
ON items.id=T.id and items.index=T.index

关于sql - 来自不同表的条件连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34714788/

相关文章:

postgresql - 在 Windows 上设置 PostgreSQL ODBC

sql - 在 SQL Server 和 Postgresql 中将 CASE 用于类似枢轴的函数

sql - 在 postgresql 中使用 meteor

c# - 在 sql server 上从 C# 运行查询

mysql - 无法选择没有重复项的最新记录

sql - 查询以按日期列表返回匹配或最近的先前记录

ruby-on-rails - rails has_one 通过关系不存在

sql - GROUP BY 如果组中至少有一个值满足条件则创建组

mysql - 在 MySQL 中获取基于月/年的所有行条目

mysql - Sql 子选择计数,其中计数相等