带有select语句的sql连接表

时间:2017-06-09 10:02:13

标签: sql join

我的表格中包含

等代码
0100 ABC
0100 ASD
9010 ABC
5555 ABC

我想创建select语句,这将为我带来两列,如

calumn A (all the codes starting with 0100), column B (all the codes that after the first 4 chars, have the same ending with column A)

例如

0100 ABC, 9010 ABC
0100 ABC, 5555 ABC
0100 ASD, null

我在想

select mtr.code, mtr1.code
from material mtr
where mtr.code like (%+

select distinct  substring(mtr.code,5, len(mtr.code)) code
from material mtr1 

)  

但当然不行。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找类似的东西:

select m1.code, m2.code
from material m1
left outer join material m2
    on substring(m1.code from 5) = substring(m2.code from 5)
    and m1.id <> m2.id
where m1.code like '0100%'

我们使用left outer join获取material的所有行,即使是没有双胞胎的行也是如此。我们的连接条件是前两个字符后两个code值必须相同。该代码还假定有一个id列;它习惯于避免将一行连接到自身。

另一方面,如果code是您的主键,则应使用m1.code <> m2.code代替。