SELECT COUNT(DISTINCT Author),COUNT(DISTINCT Author_Idents)
from location_photo
WHERE LocationID in (137697,137697,133598,133597)
SELECT count(DISTINCT(SPID))
from location_photo
WHERE LocationID in (137697,137697,133598,133597)
AND (taxonlevel="Species" OR taxonlevel="Variety" OR taxonlevel="Subspecies" OR taxonlevel="CultivatedSpecies")
我想把这两个语句合在一起,但是查询的条件不一样,应该怎么办?
我试着用了下面的语句,但是统计数一直为0
SELECT COUNT(DISTINCT Author),COUNT(DISTINCT Author_Idents) ,count(DISTINCT LocationID) , CASE WHEN taxonlevel="Species" OR taxonlevel="Variety" OR taxonlevel="Subspecies" OR taxonlevel="CultivatedSpecies" THEN COUNT(SPID) ELSE 0 END
from location_photo
WHERE LocationID in (137697,137697,133598,133597)
也试了下面的方法,但是提示语法错误
SELECT COUNT(DISTINCT Author),COUNT(DISTINCT Author_Idents) ,count(DISTINCT LocationID) , count(CASE WHEN taxonlevel="Species" OR taxonlevel="Variety" OR taxonlevel="Subspecies" OR taxonlevel="CultivatedSpecies" THEN DISTINCT(SPID) END)
from location_photo
WHERE LocationID in (137697,137697,133598,133597)
弄两个子查询,再连接,试试。
select t1.,t2.
from (SELECT COUNT(DISTINCT Author),COUNT(DISTINCT Author_Idents)
from location_photo
WHERE LocationID in (137697,137697,133598,133597)) t1,(SELECT count(DISTINCT(SPID))
from location_photo
WHERE LocationID in (137697,137697,133598,133597)
AND (taxonlevel="Species" OR taxonlevel="Variety" OR taxonlevel="Subspecies" OR taxonlevel="CultivatedSpecies")) t2
....
这样虽然可以,但是花费4秒多时间,因为表中有几百万条数据。我分开查询,每个2秒,相当于没有进行任何优化。我想一下子查出来,而且时间控制在2秒以内。或者有其他的优化方法也可以。
@寻找薛定谔的猫: 如果是应用端执行的sql,是不是可以开两个线程,并行执行,还是2秒,然后把结果在应用中拼起来。
两句合在一起很简单,使用条件一样的数据查询,不一样的部分,再处理。
首先
SELECT count(DISTINCT(SPID)),COUNT(DISTINCT Author),COUNT(DISTINCT Author_Idents),taxonlevel
from location_photo
WHERE LocationID in (137697,137697,133598,133597)
这个结果符合第一个select 语句的结果。
然后
将这个结果循环,再将 符合 这个数据 taxonlevel in ('Species','Variety','Subspecies','CultivatedSpecies') 的结果 拿出了,这个结果符合第二个select 语句的结果。
由于是COUNT,这个语句查询结果只有一条。怎么遍历?
@寻找薛定谔的猫: SELECT SPID,COUNT(DISTINCT Author),COUNT(DISTINCT Author_Idents),taxonlevel
from location_photo
WHERE LocationID in (137697,137697,133598,133597)
我的建议是,慢的原因是你用了in和or。你可以先共有条件查询出结果集,在结果集中进行筛选统计。不然,你这数据日益增多,还按此法使用in和or,查询一天比一天慢。
select COUNT(DISTINCT Author_Idents) '统计1'COUNT(DISTINCT Author) '统计2',sum(CASE WHEN taxonlevel="Species" OR taxonlevel="Variety" OR taxonlevel="Subspecies" OR taxonlevel="CultivatedSpecies" THEN 1 ELSE 0 END) '统计3' from (
selelct Author,Author_Idents,taxonlevel from location_photo where LocationID =137697
union all
------
selelct Author,Author_Idents,taxonlevel from location_photo where LocationID =133598
)newTab
纯手敲,贼麻烦了,你试试可行么。。
干嘛要合并 分开查 LocationID 也 带上 出两个datatable Merge 一下完事
问题已经解决了
将两个结果用UNION 整合
– 求索路上 5年前