+ -
当前位置:首页 → 问答吧 → 左连接

左连接

时间:2011-09-29

来源:互联网

select * from algaehistorydata a left join monthreportdata m on a.sitecode=m.sitecode and a.rmonth=m.rmonth where a.sitecode = '20029-71200002' and a.rmonth = '4' group by a.recordtime
这个是月查询的,但是我查询出来的结果集有重复项,左连接应该是已左表为准右表有符合条件的数据会查询出来,没有就用null显示,我左表有49条数据,右表有5条数据,都是4月的,左连接查询出来应该是49条,但是我查询出来的是245条,咋回事?

作者: liuchengbjaccp   发布时间: 2011-09-29

你要看看连接条件是否写完了啊。
假如你两个表有2个字段要做连接的,你只做了一个,那么左表的每一行记录都要和右表的记录连接起来,那么总记录数就是左表数量*右表数量

作者: jimmylin040   发布时间: 2011-09-29

----检查一下那个条件没有过滤掉导致的。
select * from algaehistorydata a left join monthreportdata m on a.sitecode=m.sitecode and a.rmonth=m.rmonth where a.sitecode = '20029-71200002' and a.rmonth = '4' group by a.recordtime

作者: lzd_83   发布时间: 2011-09-29

我只是查询2张表中俩字段想匹配的啊,一个是sitecode一个是rmonth,,条件都写了,还得需要写个?

作者: liuchengbjaccp   发布时间: 2011-09-29

引用 3 楼 liuchengbjaccp 的回复:
我只是查询2张表中俩字段想匹配的啊,一个是sitecode一个是rmonth,,条件都写了,还得需要写个?

select * from algaehistorydata a left join monthreportdata m on a.sitecode=m.sitecode and a.rmonth=m.rmonth where a.sitecode = '20029-71200002' and a.rmonth = '4' group by a.recordtime

从语句来看,没什么错误,应该是条件的问题.漏掉了什么?

作者: dawugui   发布时间: 2011-09-29

说下表中相同的东西吧,左表,algaehistorydata中有sietcode,recordtime,rmonth等字段
右表,monthreportdata中有sitecode,recordtime,rmonth等字段。我想查询出rmonth是4,sitecode是'20029-71200002' 的结果集,并且是左连接的。

作者: liuchengbjaccp   发布时间: 2011-09-29

那就没错.

你把left join 换成inner join 看看是什么情况?

select * from algaehistorydata a left join monthreportdata m on a.sitecode=m.sitecode and a.rmonth=m.rmonth where a.sitecode = '20029-71200002' and a.rmonth = '4' group by a.recordtime

我猜测你是碰到一对多了.

作者: dawugui   发布时间: 2011-09-29