views:

167

answers:

3

Hi All,

I have two existing tables, with different fields, except for Primary ID (a varchar, not an int). I want to create a third table which is essentially a merge of these two, such that for a given Primary Key I have all fields in one table.

What's the bext way of doing this?

Many thanks

+2  A: 

If you are sure you have one and exactly one row in both tables for a given primary ID, then this should work:

SELECT
    tablea.field1, tablea.field2, tablea.field3, ... tablea.fieldn, <---- field list
    tableb.field1, tableb.field2, tableb.field3, ... tableb.fieldm  <---- field list
FROM
    tablea, tableb
WHERE
    tablea.primaryID = tableb.primaryID

You might want to omit tablea's and tableb's primary ID field from the field list if you do not actually need them (in this query both will contain the same value due to the tablea.primaryID = tableb.primaryID condition).

The syntax is relatively similar for a VIEW as well.

Bandi-T
Yes fairly sure that there's only one row for a given PID in each table. The PID is set as PRIMARY KEY - presumably MySQL would barf on import if there was dupe?
Richard
@Richard: Yes, it would. However, for the above query to give all your rows exactly once, you also have to make sure the rows (records) can be matched exactly 1:1 to each other in the two tables. If you have a primary key of say 3 in one table, but there is no primary key 3 in the other table, there will be no row with that `3` in the result, because there is no matching `3` row in the other table.
Bandi-T
A: 
CREATE TABLE result AS (SELECT first.*, second.f1, second.f2, second.f3
                        FROM first
                          INNER JOIN second ON first.id = second.id);

To get a view, do the same except replace "TABLE" with "VIEW". If you go with the table rather than the view, make sure to add a primary key as that will not be added by deafult.

Max Shawabkeh
A: 

Why are you creating a new table? Why don't you just execute a query whenever you need the data? If you're just joining two tables on their primary key, then the majority of your data access time is going to be spent marshalling the data back to your application. You're not going to be saving much time pre-joining the tables, and you'll be eating a lot of space. Plus, you're taking aim at your big toe, just waiting for the first time you update your source tables and forget to run your update script to copy the changes to your joined table. Duplicate data is evil, but sometimes it's necessary. This doesn't sound like one of those times.

TMN