具有多列连接的 Sql 查询
Posted
技术标签:
【中文标题】具有多列连接的 Sql 查询【英文标题】:Sql query with multiple column join 【发布时间】:2014-03-09 01:07:58 【问题描述】:我遇到了一个问题:
表1
C1 C2 C3 tempId
1 4 5 ab
2 6 7 fc
3 8 9 vb
表2
ids val
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
我想传递 tempId 的值,即 ab 并希望输出类似
valofc1 valofc2 valofc3
a d e
请帮助我不知道如何实现。
【问题讨论】:
在哪个RDBMS ????是用于 SQL Server 还是 mysql 还是 SQLIte 【参考方案1】:试试这个方法:
select t21.val as valofc1, t22.val as valofc2, t23.val as valofc3
from table1 as t
join table2 as t21 on t21.ids = t.C1
join table2 as t22 on t22.ids = t.C2
join table2 as t23 on t23.ids = t.C3
where t.tempId = 'ab'
【讨论】:
【参考方案2】:试试这个
select t2.val valofc1,t3.val valofc2,t4.val valofc3 from table1 t1
inner join table2 t2 on t1.C1 = t2.ids
inner join table2 t3 on t1.C2 = t3.ids
inner join table2 t4 on t1.C3 = t4.ids
where tempId = 'ab'
DEMO HERE
【讨论】:
【参考方案3】:Declare @t table (C1 int,C2 int,C3 int,tempId varchar(50))
insert into @t values (1,4,5,'ab'),(2,6,7,'fc'),(3,8,9,'vb')
Declare @table2 table (id int,val varchar(50))
insert into @table2 values(1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e'),(6,'f'),(7,'g'),(8,'h'),(9,'i')
select
(select val from @table2 where id=t.C1)valofc1 ,
(select val from @table2 where id=t.C2)valofc2,
(select val from @table2 where id=t.C3)valofc3
from @t t where tempid='ab'
【讨论】:
以上是关于具有多列连接的 Sql 查询的主要内容,如果未能解决你的问题,请参考以下文章