SQL与两个连接表相交

时间:2016-01-12 10:16:10

标签: sql join intersect

我加入了两张桌子

SELECT 
    t1.column1, 
    t2.column2  
FROM 
    t1 JOIN t2 cu 
        ON t1.id = t2.id AND t1.col LIKE 'A%'  



SELECT
    t1.column1, 
    t2.column2  
FROM
    t1 JOIN t2 cu 
        ON t1.id = t2.id AND t1.col LIKE 'B%' 

我如何与这些表相交,以便我可以得到以下输出(具有A%和B%的ID)

加入1

id | col
---┼------
1  | Axxxx
2  | Axxxx

加入2

id | col
---┼-------
1  | Bxxxx
3  | Bxxxx

最终输出

id | col
---┼-------
1  | Axxxx
1  | Bxxxx

谢谢

3 个答案:

答案 0 :(得分:2)

如果我理解正确,你想要的只是具有A%和B%的ID,那么这就是你的答案

SELECT 
t1.column1, 
t2.column2  
FROM 
t1 JOIN t2 cu 
    ON t1.id = t2.id AND ((t1.col LIKE 'A%'  AND t2.col like 'B%')
    OR (t1.col LIKE 'B%' AND t2.col like 'A%'))

答案 1 :(得分:1)

根据您的样本,您不需要交叉,只需要简单的联合

 SELECT 
  t1.column1, 
  t2.column2  
FROM 
  t1 JOIN t2 cu 
      ON t1.id = t2.id AND t1.col LIKE 'A%'  

union

SELECT
  t1.column1, 
  t2.column2  
FROM
  t1 JOIN t2 cu 
      ON t1.id = t2.id AND t1.col LIKE 'B%' 

在你的db / sql

中修改sintax for union

答案 2 :(得分:1)

也可以这样试试......因为你正在寻找只有可重复的ID ......你可以从内部选择中算出它们

select column1, column2 from (
     select column1, column2, count(column1) over (partition by column1) [Counted] from (
        SELECT 
           t1.column1, 
           t2.column2  
        FROM 
        t1 JOIN t2 cu 
            ON t1.id = t2.id AND t1.col LIKE 'A%'
     UNION
        SELECT
           t1.column1, 
           t2.column2  
        FROM
           t1 JOIN t2 cu 
           ON t1.id = t2.id AND t1.col LIKE 'B%' 
    ) src
) src2 where Counted > 1