tags:

views:

235

answers:

3

I have two tables, ta and tb:

ta:

key col1  
--------
k1 a 
k2 c 

tb:

key col2  
-------
k2 cc 
k3 ee 

They connected by "key". I want to know how can I get a table, tc, like:

key col1 col2  
-------------
k1 a  
k2 c cc 
k3  ee

Is there a easy method instead of inserting every record? They are one million records of tables so I need an effective way. Thanks!

+2  A: 

Make a VIEW of the two tables. Write a SELECT ... JOIN statement that gives you the result you want, and then use that as the base for a VIEW.

Example:

CREATE VIEW
  database.viewname
AS
  SELECT
    ta.key, 
    ta.col1,
    tb.col2
  FROM
    ta
   LEFT JOIN
    tb
   USING(key)
Emil Vikström
This will miss the 3rd entry in the wanted table. It will need to be a FULL OUTER JOIN
Jeff Beck
Jeff, you are right. I didn't read the examples carefully. The method is the same however.
Emil Vikström
Yes I would agree.
Jeff Beck
Even if use a FULL JOIN, the "k3" still doesn't appear in column "key" of the third table. I figured out that I can use a "CASE WHEN" to adjust the column. For example:SELECT CASE WHEN ta.key IS NULL THEN tb.Key ELSE ta.Key END AS Key, ta.col1, tb.col2FROM...(full join result)Then, I can insert the result to the third table. It works, but I'm not sure whether it's an effective method.
trudger
Try: SELECT IFNULL(ta.key, tb.key) as Key ...
Emil Vikström
Thank you Emil, it makes the query string shorter.
trudger
A: 

For what you are looking for you will need to do a FULL OUTER JOIN to make sure you don't miss any keys. Once you have the query working you can think about just using it or creating a view.

You may need to work around limitations of the DB if FULL OUTER JOIN isn't implemented you can normally just UNION a left and right outer join to create your full.

Jeff Beck
A: 

Using a VIEW is the right way to go if you're looking for the data to reflect changes in the original tables.

If you do actually want the data to be copied into a new table, you'll need to do something like:

CREATE TABLE tc(key,col1,col2)

INSERT INTO tc (key,col1,col2)
SELECT ta.key, ta.col1, tb.col2
FROM ta FULL OUTER JOIN tb USING(key)

That will populate the new table with data from the old tables, but they'll be able to vary independently.

Joe Gauterin