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?
mysql - Simple SQL operation - Joining two tables with identical columns and no primary/foreign keys
2 回答
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:
The
GROUP BY
isn't needed to flatten the results because theUNION
does this naturally when selecting on all columns.Similarly, the
HAVING
isn't needed either.The column aliasing in the
UNION SELECT
query will be ignored by MySQL because the firstSELECT
list determines to column names for the result. All you need for aUNION
is (a) the same number of columns in allSELECT
statements and (b) compatible data types for the corresponding columns - either the same or implicitly castable.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