在SQL中组合查询

时间:2013-06-05 15:48:56

标签: sql

尝试返回MOF和SIL位置中存在的标题列表(t.processed),然后从SIL中存在的该列表中删除标题

修:

select t.processed, i.call
from item i, title t
where i.bib# = t.bib#
    and i.collection = 'PIC'
    and i.location in ('MOF', 'SIL')
except
select t.processed, i.call
from item i, title t
where i.bib# = t.bib#
    and i.collection = 'PIC'
    and i.location = 'SIL'

不幸的是,这没有结果,但它更接近我的需要

示例输出相当简单(且灵活):

processed        call
Mouse count      P WAL
Fly away home    P BUN

进一步说明:我想找到在SIL和MOF位置重复的标题(例如Fly away home),然后从该列表中删除SIL位置中出现的标题

4 个答案:

答案 0 :(得分:1)

假设Item类似于

ID Item Collection Location
1  1    PIC        MOF
2  1    PIC        SIL
3  2    PIC        MOF
4  3    PIC        SIL

然后

Select select mof.item#, mof.call, mof.collection From Item mof
Left Join Item sil On mof.Item# = sil.Item# and sil.Collection = mof.Collection
Where sil.Location = 'SIL'
and mof.Location = 'MOF'
and mof.Collection = 'PIC'
and sil.ID is null

会让你走近。停止使用旧的连接语法...

答案 1 :(得分:0)

EXCEPT运算符执行此操作,至少对于某些类型的SQL:

select i.item#, t.processed, i.call, i.collection
from item i, title t
where i.bib# = t.bib#
    and i.collection = 'PIC'
    and i.location = 'MOF'
except
select i.item#, t.processed, i.call, i.collection
from item i, title t
where i.bib# = t.bib#
    and i.collection = 'PIC'
    and i.location = 'SIL'

答案 2 :(得分:0)

尝试

select i.item#, t.processed, i.call, i.collection
from item i, title t
where i.bib# = t.bib#
    and (
         (i.collection = 'PIC' and i.location <> 'SIL') 
         or ( i.collection = 'PIC' and  i.location = 'MOF')
        )

答案 3 :(得分:0)

最终编辑:

这是我正在寻找的查询(对于没有充分解释自己而道歉)

select t.processed
from title t, item i
where t.bib# = i.bib#
and i.location = 'MOF'
and i.collection = 'PIC'
and i.bib# not in (select bib# from item where location = 'SIL' and collection = 'PIC')

我仍然无法绕过子查询。我的麻烦在于没有使用主键i.bib#作为子查询的基础。

感谢大家的建议!