开发者

SQL - Join Two Tables About The Same Entities

开发者 https://www.devze.com 2023-02-15 10:29 出处:网络
I have created two tables, each table contains some entries that are about the same entity. How can I write a query to join the entries and create a unified entry in another 开发者_JAVA百科table?

I have created two tables, each table contains some entries that are about the same entity. How can I write a query to join the entries and create a unified entry in another 开发者_JAVA百科table?

sorry for the confusion guys. I should provide a simple example.

My two tables look similar to the below,

Table 1: Name, ID, email, city, state, phone

Table 2: LastName, FirstName, email, gender, ID


I assume that ID is the primary key that links the two tables. This query takes selected columns from each table and inserts them into table @U3.


declare @U3 Table(ID int, FirstName varchar(50), LastName varchar(50),  
                  city varchar(50), [state] varchar(50), phone varchar(50),
                  email varchar(50), gender varchar(50))

insert @U3
  select u1.ID, u2.FirstName, u2.LastName, u1.email,
         u1.city, u1.state,u1.phone, u2.gender
  from Table1 u1 
    join Table2 u2 on u2.ID=u1.ID

select * from @U3


Something like:

INSERT INTO
    c (machine, address)
(   SELECT
           a.machine, a.address
    FROM
           a
    UNION
    SELECT
           b.machine, b.address
    FROM
           b
);


INSERT INTO TableC VALUES (SELECT T1.Name,T1.email,T1.city,T1.state,T1.phone,
T2.Lastname,T2.Firstname,T2.gender FROM Table1 T1 
LEFT JOIN Table2 T2 ON T1.ID = T2.ID)

Table C should contain all fields in the result set of the join of Tables 1 and 2. except for the duplicate ID/email

Edited to show all fields

0

精彩评论

暂无评论...
验证码 换一张
取 消