两个表的连接
表1
id date price mile
1 20:00 120 529
2 10:00 110 500
3 23:00 60 200
4 18:00 28 90
5 15:30 96 300
表2
id date FName TelNum
2 10:00 李 13978963833
3 23:00 杨 13869878968
6 17:30 朱 13068678963
如何连接表1和表2得到以下:
id date price mile FName telnum
1 20:00 120 529
2 10:00 110 500 李 13978963833
3 23:00 60 200 杨 13869878968
4 18:00 28 90
5 15:30 96 300
也就是表1包含表2,这样把2个表连接起来
[解决办法]
create table t1 (id int, date char(5), price int, mile int)
create table t2 (id int, date char(5), FName varchar(20), TelNum varchar(20))
insert t1
select '1 ', '20:00 ', '120 ', '529 '
union all
select '2 ', '10:00 ', '110 ', '500 '
union all
select '3 ', '23:00 ', '60 ', '200 '
union all
select '4 ', '18:00 ', '28 ', '90 '
union all
select '5 ', '15:30 ', '96 ', '300 '
insert t2
select '2 ', '10:00 ', '李 ', '13978963833 '
union all
select '3 ', '23:00 ', '杨 ', '13869878968 '
union all
select '6 ', '17:30 ', '朱 ', '13068678963 '
select t1.id, t1.date, t1.price, t1.mile, t2.FName, t2.TelNum from t1 left join t2 on t1.date=t2.date
结果
id date price mile FName TelNum
----------- ----- ----------- ----------- -------------------- --------------------
1 20:00 120 529 NULL NULL
2 10:00 110 500 李 13978963833
3 23:00 60 200 杨 13869878968
4 18:00 28 90 NULL NULL
5 15:30 96 300 NULL NULL
(所影响的行数为 5 行)
[解决办法]
select * from 表1 a left join 表2 b on a.date=b.date