2008-10-29 66 views
1

我正在检查in_fmd中的一行的存在情况,并且查找的ISBN可以是ISBN参数,也可以是交叉表中另一个可能有或没有一行的ISBN。如何改进此SQL查询?

select count(*) 
from in_fmd i 
where (description='GN') 
    and (i.isbn in 
    (
     select bwi_isbn from bw_isbn where orig_isbn = ? 
     union all 
     select cast(? as varchar) as isbn 
    ) 
) 

我实际上并不关心行数,而只是至少存在一行。

这曾经是三个独立的查询,我把它压扁成一个,但我认为还有进一步改进的余地。它是PostgreSQL 8.1,如果它很重要。

+0

作为旁注,我们不再使用此查询。 in_fmd表已被删除,我们不必再合成数据点。该查询是最快的,它不运行。 :-) – 2010-09-16 21:59:40

回答

4

为什么与UNION ALL

select count(*) 
from in_fmd i 
where (description='GN') 
    and (
     i.isbn in (
      select bwi_isbn from bw_isbn where orig_isbn = ? 
     ) 
     or i.isbn = cast(? as varchar) 
    ) 

打扰我可能会使用一个LEFT JOIN式的查询,而不是IN,但是这更多的个人喜好:

select count(*) 
from in_fmd i 
left join bw_isbn 
    on bw_isbn.bwi_isbn = i.isbn 
    and bw_isbn.orig_isbn = ? 
where (i.description='GN') 
    and (
     bw_isbn.bwi_isbn is not null 
     or i.isbn = cast(? as varchar) 
    ) 

通过IM讨论的反转:

SELECT SUM(ct) 
FROM (
    select count(*) as ct 
    from in_fmd i 
    inner join bw_isbn 
     on bw_isbn.bwi_isbn = i.isbn 
     and bw_isbn.orig_isbn = ? 
     and i.isbn <> cast(? as varchar) 
     and i.description = 'GN' 

    UNION 

    select count(*) as ct 
    from in_fmd i 
    where i.isbn = cast(? as varchar) 
     and i.description = 'GN' 
) AS x 
0
select count(*) 
from in_fmd i 
where description = 'GN' 
    and exists (select 1 
       from bwi_isbn 
       where bw_isbn.bwi_isbn = in_fmd.isbn) 
+0

尽管此代码片段可能会解决问题,但并不能解释为什么或如何回答问题。请包含您的代码的说明,因为这有助于提高帖子的质量。请记住,您将在未来向读者回答这个问题,而这些人可能不知道您的代码建议的原因。 – 2017-09-08 06:36:49

1

我其实并不关心行数,而只是至少存在一行。

那么如何查询SELECT ... LIMIT 1并在调用程序中检查您是否得到一个结果行?

+0

我只能保存最多2行中的1行。我希望少看一些。 – 2008-10-29 19:28:51

1
SELECT SUM(ct) 
FROM (select count(*) as ct 
     from in_fmd i 
     inner join bw_isbn 
     on bw_isbn.bwi_isbn = i.isbn 
     and bw_isbn.orig_isbn = ? 
     and i.isbn <> cast(? as varchar) 
     and i.description = 'GN' 
     UNION 
     select count(*) as ct 
     from in_fmd i 
     where i.isbn = cast(? as varchar) 
     and i.description = 'GN' 
    ) AS x 
1

除了什么其他海报指出,只是改变

SELECT COUNT(*)

存在(..)

improve things颇有几分