【数据库面试题】 1 - SQL基础 - 联结表

1. A,B,C,D四张表的结构相同,都包含四个字段:id, name, address, age;

Q1:存在于A表中,不存在于B表和D表中的数据

Q2:将不属于表D的但是在表A中的数据插入到表B中去


A1: 查询在一张表不在另一张表中的记录:

首先将表B和D组合(UNION),然后从A表中去掉组合表中的记录;

首先想到的是使用not in的方法,e.g. select * from table where column not in (another table set);当这样做相当于表a中字段都要遍历一次b表,效率低下。

方法1:使用外连接

select A.* from A left join (select * from B union select * from D) as TEMP on A.id = TEMP.id and A.name = TEMP.name and A.age = TEMP.age and A.addresss = TEMP.addresss where TEMP.id IS NULL  

方法2:sql server中,使用关键字 EXCEPT

select A.* from A except (select * from B union select * from D) 

表A:
id	name	addresss	age
1	a	    adda	    10
2	b	    addb	    11
3	c	    addc	    12

表B:
id	name	addresss	age
3	TEST	addc	    12

表D:
id	name	addresss	age
2	b	    addb	    11

结果:
id	name	addresss	age
1	a	    adda	    10
3	c	    addc	    12

A2

insert into B select A.* from A left join D on A.id = D.id and A.name = D.name and A.age = D.age and A.addresss = D.addresss where D.id IS NULL and A.id not in (select id from B)


2. 表A与表B结构一致,现找出表B中,表B与表A的三个对应字段中有两个对应字段相等的记录:

如:

表A
col1	col2	col3
1	    10	    100
2	    20	    200
3	    30	    300
4	    40	    400

表B
col1	col2	col3
1	    20	    1
2	    20	    222
1	    102	    111
3	    30	    300
9	    40	    400

输出:

col1	col2	col3
2	    20	    222
3	    30	    300
9	    40	    400

select B.* from B left join A on (
(B.col1 = A.col1 and B.col2 = A.col2) or
(B.col2 = A.col2 and B.col3 = A.col3) or
(B.col1 = A.col1 and B.col3 = A.col3) ) 
where A.col1 is not null


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值