对于如下的表结构:
tb1:
key value
1 2
2 3
3 4
tb2:
key time
1 9
2 5对于查询语句如下:
select tb1.key,tb1.value,tb2.time
from tb1,tb2
where tb1.key=tb2.key
那么显示结果应为:
key value time
1 2 9
2 3 5对于key值为3的记录就不会显示
现在要求对于tb1中的每条记录,都能查出一条接过来,如果对于的key值在tb2中没有,
就显示空值,或者默认填某个值,例如0
有没有方法达到这个目的谢谢达人指点。
tb1:
key value
1 2
2 3
3 4
tb2:
key time
1 9
2 5对于查询语句如下:
select tb1.key,tb1.value,tb2.time
from tb1,tb2
where tb1.key=tb2.key
那么显示结果应为:
key value time
1 2 9
2 3 5对于key值为3的记录就不会显示
现在要求对于tb1中的每条记录,都能查出一条接过来,如果对于的key值在tb2中没有,
就显示空值,或者默认填某个值,例如0
有没有方法达到这个目的谢谢达人指点。
drop table if exists tb2;create table tb1(
`key` int,
`value` int
)engine=innodb;
create table tb2(
`key` int,
`time` int
)engine=innodb;insert into tb1 values(1,2);
insert into tb1 values(2,3);
insert into tb1 values(3,4);insert into tb2 values(1,9);
insert into tb2 values(2,5);select distinct tb1.`key`,tb1.`value`,tb2.`time`
from tb1 left join tb2
on tb1.`key`=tb2.`key`
create table tb1(
`key` int,
`value` int
)engine=myisam;
create table tb2(
`key` int,
`time` int
)engine=myisam;insert into tb1 values(1,2),(2,3),(3,4);insert into tb2 values(1,9),(2,5);
select tb1.key,tb1.value,(case when tb2.time is null then 0 else tb2.time end) `time` from tb1 left join tb2 on tb1.key = tb2.key;query result(3 records)
key value time
1 2 9
2 3 5
3 4 0 drop table tb1;
drop table tb2;