读书人

left join 后的表多条记录.取1.解决方

发布时间: 2012-01-15 22:57:48 作者: rapoo

left join 后的表多条记录.取1.
alist主表.记录每样物品的详细信息.
bopen次表.记录用户每次打开物品的记录.
每次A用户或B用户打开BOPEN后,BOPEN就会生产一条记录.
SQL生成了一个
case when not XXXX is null then '1 ' else '0 ' end ynopen
如果有记录ynopen的值就为1,如果没有记录ynopen就为0

现用
select alist.id as aid,
case when not b.autoid is null then '1 ' else '0 ' end YNopen
from alist left join bopen on alist.id=b.id
where 条件语句
如此一来,会出现大量结果
于是就用了distinct进行精简重复的

select alist.id as aid,
case when not b.id is null then '1 ' else '0 ' end YNopen
from alist left join bopen on alist.id=b.id and username= 'a '
where 条件语句

(主alist有2万多条记录.bopen打开记录也有1万条(以后会增加到上百万))
用distinct精简后,可以实现ynopen的效果,但速度非常慢,平均会用7秒的时间.
其实对比的时候,我只需要判断bopen是否有用户的记录即可,如何写?
如果有记录,ynopen就为1,没有就为0,以标示用户是否打开过.

[解决办法]
或者

select alist.id as aid,
case when not b.autoid is null then '1 ' else '0 ' end YNopen
from alist left join (Select id, Max(autoid) As autoid From bopen Group By id) b on alist.id=b.id

读书人网 >SQL Server

热点推荐