从表中只选择一个特定值

时间:2014-03-19 09:26:58

标签: sql select join

我有3张桌子:

  • Duties
  • Activities
  • Activity Types

一项职责有一项或多项活动,一项活动有多种活动类型。

例如我有2个职责:

  1. 值班1有2项活动。活动类型为“TYPE1”的活动1,活动类型为“TYPE2”的活动2。
  2. Duty 2有2项活动,两项活动都有活动类型“TYPE2”。
  3. 我希望我的select语句使用“TYPE2”检索所有职责,但如果职责具有活动类型为“TYPE1”,“TYPE2”或任何其他类型的活动,则不应选择它们。即只选择所有活动都有活动类型“TYPE2”的职责。

    这是我当前的查询:

    select columns from duties d
    join activity a on d.duty_id = a.id
    join activity_type t on t.id = a.act_id and activity_type = 'TYPE2'
    

2 个答案:

答案 0 :(得分:1)

你可以用子查询来支付它,这是可读的方式:"所有具有Type2活动的职责,没有其他类型的活动"

select distinct columns 
from duties d
join activity a2 on d.duty_id = a2.id
join activity_type t2 on t2.id = a2.act_id and activity_type = 'TYPE2'
where d.duty_id not in
( select duty_id.id from duties d
  join activity a on d.duty_id = a.id
  join activity_type t on t.id = a.act_id and activity_type <> 'TYPE2' 
)

请注意,此类查询的性能不高,因为每个主查询行都会执行子查询。

没有标准sql中的子查询:

select columns 
from 
  (
    select columns (including duty_id )
    from duties d
    join activity a on d.duty_id = a.id
    join activity_type t on t.id = a.act_id and activity_type = 'TYPE2'
  ) as yesT2
left outer join
  (
    select distinct d.duty_id 
    from duties d
    join activity a on d.duty_id = a.id
    join activity_type t on t.id = a.act_id and activity_type <> 'TYPE2'
  ) as yesT1
on 
  yesT2.duty_id = yesT1.duty_id
where
  yesT1.duty_id is Null

可读性可提高我们的数据库品牌支持CTE。

答案 1 :(得分:1)

select duty_name from duty
except
select duty_name from duties d
join activity a on d.duty_id = a.id
join activity_type t on t.id = a.act_id and activity_type <> 'TYPE2'

这将排除任何具有其他活动类型的活动