mysql - 复杂条件连接

标签 mysql sql sql-server oracle11g

Table B
PropertyID  Property
40      (old)  Retirement 
40      (old)  Retirement 
40      (old)  Retirement 
40      (old)  Retirement 
40      (old)  Retirement 

Table A

ProplistID  ProplistCode    ProplistName    PropertyID  PropertyCode PropertyName
101 evergree    Evergreen   30  453 Retirement Center
101 evergree    Evergreen   31  454 Retirement Community
101 evergree    Evergreen   32  443 Retirement Center
101 evergree    Evergreen   33  444 Retirement Community

我的查询

SELECT  t1.*, t2.PropertyCode 
FROM    Test.dbo.Table A T1 
        INNER JOIN Test.dbo.Table T2 ON T1.PropertyID = T2.ProplistID;

UNION ALL 

SELECT t1.*, t2.PropertyCode
FROM   Test.dbo.TABLE A T1
       INNER JOIN Test.dbo.TABLE B T2 ON T1.PropertyID = T2.PropertyID; 

ORDER BY 1

您好,我正在尝试进行这个复杂的连接。

我有两张 table

**

  • 表 1

**

Col A   Col B
1       3
2           11
3           1
4           11
5           3
6           3
7           11

**

  • 表 2

**

表2

Col A   Col B   Col C   Col D
1   Hello   3   Bye
2   Hello   4   Bye
5   Hello   6   Bye
7   Hello   11  Bye
8   Hello   12  Bye
9   Hello   13  Bye
20  Hello   14  Bye

我需要加入他们才能获得下面提到的表格

Col A   Col B   Col C
1   3   Hello
2   11  Hello
3   1   Bye
4   11  Bye
5   3   Hello
6   3   Bye
7   11  Hello

表 1 A 列有一些 ID 在 B 列中对应值为 3 或 11

表需要连接为

如果(表 1.Col A.Value = 3)

所以表 3.C 列 = 你好

然后加入(表 1.Col A = 表 2.Col A)

其他(表 1.Col A.Value = 3)

然后加入(表 1.A 列 = 表 2.C 列)

所以表 3.C 栏 = 再见

请帮我解决这个问题。

最佳答案

create table #t1 (ColA int,  ColB int)
insert #t1 values
(1,  3),
(2, 11),
(3,  1),
(4, 11),
(5,  3),
(6,  3),
(7, 11)

create table #t2 (ColA int,  ColB char(5), ColC int,  ColD char(3))
insert #t2 values
(1 ,  'Hello',   3 ,  'Bye'),
(2 ,  'Hello',   4 ,  'Bye'),
(5 ,  'Hello',   6 ,  'Bye'),
(7 ,  'Hello',   11,  'Bye'),
(8 ,  'Hello',   12,  'Bye'),
(9 ,  'Hello',   13,  'Bye'),
(20,  'Hello',   14,  'Bye')


select #t1.cola, #t1.colb, #t2.colb
from #t1
inner join #t2
on #t1.cola = #t2.cola 
union all
select #t1.cola, #t1.colb, #t2.cold
from #t1
inner join #t2
on #t1.cola = #t2.colc 
order by 1

关于mysql - 复杂条件连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480222/

相关文章:

php - 在 MySQL 中使用绑定(bind)参数作为用户定义的变量是否安全?

php - 从产品表中获取数据,其中类别值以序列化格式存储

SQL Server Management Studio 2008 Runas 用户在不同的域上通过 VPN

sql-server - 获取链接服务器状态的存储过程

Mysql插入外键

php - 如何处理条件为 'IN' 的 PHP API POST select 语句?

sql - 在 SQL 中使用人类可读的主键是否安全?

sql - 处理空白查询结果,ISNULL(NULLIF())

sql-server - 我该如何做类似 : USE @databaseName 的事情

mysql - 如何在 Python3 中将输入转义到 MySQL 数据库?