0

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?

4

2 回答 2

1

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
于 2013-05-28T14:54:20.260 回答
1

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
于 2013-05-28T15:14:10.563 回答