我的表结构是这样的:
sch_id daynum sched_hrs
123 1 7
123 2 6.5
123 3 5
456 1 8
456 2 4
456 3 3
我想创建一个查询,它将为我提供所有时间表where
daynum = 1 and sched_hrs = 7 and daynum = 2 and sched_hrs = 6.5
。
我正在尝试这种方法,但没有运气好
select distinct sch_id from table
where (daynum,sched_hrs) in (('1', '7')) and (daynum,sched_hrs) in (('2','6.5')) .
答案 0 :(得分:1)
这应该会给你正确的结果:
select sch_id from table t1 join t2 on t1.sch_id =t2.sch_id
where t1.daynum =1 and t1.sched_hrs = 7 and t2.daynum =2 and t2.sched_hrs = 6.5
答案 1 :(得分:1)
鉴于您的各种评论,您实际上正在搜索"sch_id"
第一天的sched_hrs
为7,第二天的sched_hrs
为6.5。
如果是这样,您可以使用自联接来解决这个问题:
SELECT "sch_id" FROM T t1 JOIN T t2 USING("sch_id")
WHERE t1."daynum" = 1 AND t1."sched_hrs" = 7
AND t2."daynum" = 2 AND t2."sched_hrs" = 6.5
答案 2 :(得分:1)
如果我理解正确,你想要的是OR
:
WHERE ( daynum = 1 AND sched_hrs = 7 ) OR ( daynum = 2 AND sched_hrs = 6.5 )
我在上面使用过括号,即使在这种情况下它们并非绝对必要(AND
优先于OR
)。
您也可以使用IN
(应该给出相同的结果):
WHERE (daynum, sched_hrs) IN ( (1, 7), (2, 6.5) )
答案 3 :(得分:0)
你可以试试;
select sch_id
from table
where daynum in (1, 2)
and sched_hrs in (7, 6.5)
答案 4 :(得分:0)
select * from test where daynum=1 and sched_hrs = 7 and sch_id in (select sch_id from test where daynum=1 )
union
select * from test where daynum=2 and sched_hrs = 6.5 and sch_id in (select sch_id from test where daynum=2 )
答案 5 :(得分:0)
也许你想要这个:
select * from t t1 where daynum=1 and sched_hrs = 7 and
exists (select 1 from t where sch_id = t1.sch_id and daynum=2 and sched_hrs = 6.5)
union all
select * from t t1 where daynum=2 and sched_hrs = 6.5 and
exists (select 1 from t where sch_id = t1.sch_id and daynum=1 and sched_hrs = 7)
答案 6 :(得分:0)
如果我理解你的问题,一个简单的UNION会抓住你想要的所有记录:
select sch_id,daynum,sched_hrs from table where daynum = '1' and sched_hrs = '7'
union
select sch_id,daynum,sched_hrs from table where daynum = '2' and sched_hrs = '6.5';