Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL效率优化,O(n^2)时间复杂度,如何简化?_Sql_Database - Fatal编程技术网

SQL效率优化,O(n^2)时间复杂度,如何简化?

SQL效率优化,O(n^2)时间复杂度,如何简化?,sql,database,Sql,Database,我不熟悉SQL,但我正在尝试编写一个尽可能简单的查询。这是一个简单的查询,用于计算attr“tag”具有相同“jobid”的概率。我知道这是一个糟糕的编码,因为枚举数和分子是一次又一次(即每次)重复计算的 有没有简单的O(n)查询?(简单的意思是不要用很多子句,比如WITH等)尽量简单地 insert into probclass (jobid, tag, probability) (select s1.jobid, s1.tag, (select count(*) from sqls

我不熟悉SQL,但我正在尝试编写一个尽可能简单的查询。这是一个简单的查询,用于计算attr“tag”具有相同“jobid”的概率。我知道这是一个糟糕的编码,因为枚举数和分子是一次又一次(即每次)重复计算的

有没有简单的O(n)查询?(简单的意思是不要用很多子句,比如
WITH
等)

尽量简单地

insert into probclass (jobid, tag, probability) 
    (select s1.jobid, s1.tag, (select count(*) from sqlset as s2 
                             where s1.jobid = s2.jobid and s1.tag = s2.tag)
                            /
                            (select count(*) from sqlset as s3 
                             where s1.jobid = s3.jobid) 
     from sqlset as s1)

如果两个都是不同表的不同计数值 然后


您使用的是MySQL还是MS SQL Server?(请不要标记未涉及的产品。)对于这个特定的查询,是否有一个通用的可编译版本?可能有,如果您想得到答案,SQL标记就足够了。如果您的数据库产品支持窗口聚合,则有一个简单的(ish)答案。是的,不是。也许我对你的模式感到困惑,但是这个查询怎么会不返回概率为1呢?分子是
,其中s1.id=s2.id和s1.tag=s2.tag
id
不是您的主键吗?
     select count(*) as 'count1' into #temp1 from sqlset as s2 
     where s1.id = s2.id and s1.tag = s2.tag
     select count(*) as 'count2' into #temp2 from sqlset as s3 
     where s1.id = s3.id
     insert into probclass (id, tag, probability) 
    (select s1.id, s1.tag, (select count1 from #temp1/select count2 from #te,p2))