Combine two tables in SQLite

2020-02-11 05:58发布

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.

标签: sqlite join
3条回答
我只想做你的唯一
2楼-- · 2020-02-11 06:14

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)
查看更多
叼着烟拽天下
3楼-- · 2020-02-11 06:26

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.

查看更多
够拽才男人
4楼-- · 2020-02-11 06:40

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.

查看更多
登录 后发表回答