简体   繁体   中英

How to query 2 tables in sql server with many to many relationship to identify differences

I have two tables with a many to many relationship and I am trying to merge the 2 tables in a select statement. I want to see all of the records from both tables, but only match 1 record from table A to 1 record to table b, so null values are ok.

For example table A has 20 records that match only 15 records from table B. I want to see all 20 records, the 5 that are unable to be matched can show null.

Table 1

Something | Code#

apple | 75
pizza | 75
orange | 6
Ball | 75
green | 4
red | 6

Table 2

date | id#

Feb-15 | 75
Feb-11 | 75
Jan-10 | 6
Apr-08 | 4

The result I need is

Something | Date | Code# | ID#


apple | Feb-15 | 75 | 75
pizza | Feb-11 | 75 | 75
orange | Jan-10 | 6 | 6
Ball | NULL | 75 | NULL
green | Apr-08 | 4 | 4
red | NULL | 6 | NULL

A regular Left-join should do it for you.

select tableA.*
     , tableB.*
  from tableA
left join tableB
       on tableB.PrimaryKey = tableA.PrimaryKey

I'm imagining something like this. You want to pair of the rows side by side but one side is going to have more than the others.

select * /* change to whatever you need */
from
    (
        select *, row_number() over (partition by "code#" order by "something") as rn
        from tableA
    ) as a
        full outer join /* sounds like maybe left outer join will work too */
    (
        select *, row_number() over (partition by "id#" order by "date" desc) as rn
        from tableB
    ) as b
        on b."id#" = a."code#" and b.rn = a.rn

Actually I don't know how you're going to get "ball" to comes after "apple" and "pizza" without some other column to sort on. Rows in SQL tables don't have any ordering and you can't rely on the default listing from select *... or assume that the order of insertion is significant.

Left outer join
Question changed
Make that a full outer join

select table1.*, table2.* 
  from table1 
  full outer join table2  
    on table1.Code# = table2.id#

This is probably not a true many to many but I think this is what you are asking for

we would need to see the table structure to tell you for sure, but essentially you join on the full key (if possible)

SELECT * FROM TABLEA A

JOIN TABLEB B ON
A.FULLKEY = B.FULLKEY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM