简体   繁体   中英

Simple SQL operation - Joining two tables with identical columns and no primary/foreign keys

I have two tables with identical (6) columns, and varying entries. I would like to obtain a "master" table with the same columns, including every unique entry from table A and B. There exists no primary or foreign keys on either table, and the "uniqueness" of an entry is determined by each of the 6 fields being identical to another entry. In other words, if entry x has column 1 equal to entry y's column 1, and all remaining columns are equal as well, these two entries are considered non-unique, whether they exist in the same table or separate tables. I've researched and found similar solutions, but none that quite solve this issue. Any thoughts?

You can just use a union statement:

(
    SELECT column1 AS column1, column2 AS column2, column3 AS column3  
    FROM table1 
) UNION (
    SELECT column1 AS column1, column2 AS column2, column3 AS column3 
    FROM table2 
)
GROUP BY column1, column2, column3 
HAVING COUNT(column1, column2, column3)>0

A UNION is definitely what's needed here, but there are a few extraneous items in the query from @PhilCross:

  1. The GROUP BY isn't needed to flatten the results because the UNION does this naturally when selecting on all columns.

  2. Similarly, the HAVING isn't needed either.

  3. The column aliasing in the UNION SELECT query will be ignored by MySQL because the first SELECT list determines to column names for the result. All you need for a UNION is (a) the same number of columns in all SELECT statements and (b) compatible data types for the corresponding columns - either the same or implicitly castable.

  4. The parentheses aren't needed either, but you should include them if it makes the query more readable for you.

So all you really need is the following:

SELECT column1 AS column1, column2 AS column2, column3 AS column3
FROM table1
UNION SELECT column1, column2, column3
FROM table2

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