Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

sql - Join two tables based on two columns

Hi my SQL is a bit rusty and need a bit help with getting a statement correct. I have the following setup table A and B:

  A        B
=====    ======
  A       A  B
  B       C  B
          A  C
          B  D
          D  A

I would like to JOIN the single column on A with both columns on B to end up with table C:

  C
=====
  A
  A
  B
  B
  B
  A

I have tried different joins, but when I use the OR operator I get way to many rows. My Setup is a bit more advanced, I hope the simplified tables above is enough to illustrate my issue. My setup is a bit more advanced in the above example. In my real world application I have two tables where I have to find all the multiple phone numbers, which can be in two columns, PHONE1 and PHONE3. First I make a intersection so I get all the phone numbers, which are represented more than once. My problem is I need to end up with a statement that return all the multiplets, and some extra data from the other columns. Here is my statement:

SELECT * FROM
(SELECT COMPANY, CONTACT, PHONE1, PHONE3, U_EMAIL, UMEDLEM, UKONKAT, UAAFMELD
FROM CONTACT1 JOIN CONTACT2 on CONTACT1.ACCOUNTNO = CONTACT2.ACCOUNTNO) as t1
INNER JOIN
(SELECT PHONE1 as PHONE FROM CONTACT1 WHERE LEN(PHONE1) > 0
INTERSECT
SELECT PHONE3 FROM CONTACT1 WHERE LEN(PHONE1) > 0) as t2 ON t1.PHONE1 = t2.PHONE
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

this is how you could join A's column on Both columns of B.

SELECT * FROM A
INNER JOIN B B1 ON A.Column1 = B1.Column1 
INNER JOIN B B2 ON A.Column1 = B2.Column2 

Or you can use UNION, to combine two query results

SELECT * FROM A
INNER JOIN B  ON A.Column1 = B.Column1 
UNION
SELECT * FROM A
INNER JOIN B  ON A.Column1 = B.Column2 

you can also consider LEFT joins, depending on how you want to handle NULL values in B.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...