我有两张桌子:
T1:
SSN NAME LAST AD SAL
-------------- ---------- ---------- ----- ----------
s1 paps 2600
s2 raj 1500
s3 rahul
T2:
SSN NAME LAST AD SAL
---------- ---------- ---------- ----- ----------
s1 mukh sbc
s2 sar mdn
s3 das tly 1100
我想将这两个表合并为一个类似
的表T3:
ssn name last ad sal
---- ----- ----- ---- ----
s1 paps mukh sbc 2600
s2 raj sar mdn 1500
s3 rahul das tly 1100
我该怎么做?
答案 0 :(得分:2)
你有4种不同的方法来合并一个表。
一个简单的连接:
TSQL
使用视图:
create or replace view t3 as
select ssn, t1.name, t2.last, t2.ad, MAX(t1.sal, t2.sal)
from t1, t2
where t1.ssn = t2.ssn;
或创建一个新表,并插入另外两个的值
create table t3 (ssn, name, last, ad, sal);
insert into t3 select ssn, t1.name, t2.last, t2.ad, MAX(t1.sal, t2.sal)
from t1, t2
where t1.ssn = t2.ssn;
你可以选择武器! : - )
关于查询,您可能希望进行比我在示例中所写的更复杂的连接,即:
select *
from t1, t2
where t1.ssn = t2.ssn
and t1.name = t2.name
and (t1.last = t2.last
or t1.ad = t2.ad
or t1.sal = t2.sal);
因为我在t3连接表的值中没有真正得到逻辑,所以我并不真正看到你想要的条件。比如广告中包含来自无处的abc
字符串。但您可以在上一个查询中将AND
替换为OR
以更改选择行为,并添加IF()
表达式以选择值...
好的,那么这里是可能符合您需求的已审核查询(如果sal
是一个数字):
select t1.ssn, t1.name, t2.last, t2.ad, MAX(t1.sal, t2.sal)
from t1, t2
where t1.ssn = t2.ssn;
或
select t1.ssn as ssn,
t1.name as name,
t2.last as last ,
t2.ad as ad,
if(t1.sal is null,t2.sal,t1.sal) as sal
from t1, t2
where t1.ssn = t2.ssn;
或
select t1.ssn as ssn,
t1.name as name,
t2.last as last ,
t2.ad as ad,
case when s1.sal is null
then s2.sal
else s1.sal
end as sal
from t1, t2
where t1.ssn = t2.ssn;
答案 1 :(得分:1)
你说你想要“合并”表格,但你没有给出足够的细节来给出一个没有一些假设的自信答案。想到三个问题:
根据您的数据,我会说Table1具有优先权。我不想从只有三行的样本中假设(2)。我假设(3)因为这就是数据的结构。
所以,这样做的方法是full outer join
:
select coalesce(t1.ss1, t2.ssn) as ssn, t1.NAME,
coalesce(t1.last, t2.name) as last,
coalesce(t1.ad, t2.last) as ad,
coalesce(t1.sal, t2.sal) as sal
from table1 t1 full outer join
table2 t2
on t1.ssn = t2.ssn;
答案 2 :(得分:0)
SELECT
*
FROM t1
UNION ALL
SELECT
*
FROM t2
答案 3 :(得分:0)
根据您在t3
中显示的数据,我在t1
和t2
之间假设以下关系,映射到t3
:
t3.ssn = (t1.ssn && t2.ssn)
t3.name = t1.name
t3.last = t2.name
t3.ad = t2.last
t3.sal = t1.sal, unless null; t2.sal otherwise
如果这些匹配正确,您应该可以从t1
和t2
提取数据,并使用以下查询将其插入t3
:
INSERT INTO t3 (ssn, name, last, ad, sal) (
SELECT
t1.ssn, t1.name, t2.name, t2.last, IF(t1.sal IS NOT NULL, t1.sal, t2.sal)
FROM
t1
JOIN t2 ON t1.ssn = t2.ssn
);
答案 4 :(得分:0)
SELECT t1.ssn,t1.name,t2.name,t2.ad,t1.sal FROM table t1 JOIN table t2 on t1.ssn=t2.ssn
试试这个,看看