如何从表中获取两次字段(在不同条件下)?

时间:2011-04-05 21:27:37

标签: mysql

我有一个名为Reader的表,其id,date,time作为其字段。时间字段包含员工的及时和退出时间,因此我希望根据特定ID和日期范围的2个条件检索两次出现的值:

1.In-time:Time between '9:00:00' and '12:00:00'
2.Out-time:Time between '15:00:00' and '19:00:00'

Command应该看起来像这样

select id,tim,tim,dat from reader 
where tim between '09:00:00' and '14:00:00' 
and   tim between '15:00:00' and '17:00:00' 
and dat between '2011-01-17' and '2011-01-19' 
and id =10704 ;

3 个答案:

答案 0 :(得分:1)

select id,tim,dat from reader 
where ((tim between '09:00:00' and '14:00:00')
    or (tim between '15:00:00' and '17:00:00'))
and dat between '2011-01-17' and '2011-01-19' 
and id =10704 ;

您需要在时间之间进行OR,而不是AND,因为它永远不可能在两个非相交范围内。确保将条件的那部分括起来,否则你的AND / OR将无法正常工作。

以上为您提供单独行中的数据。 为了让它们在同一记录上保持平坦,你可以使用,假设每天每个范围只有一次

select rin.id,rin.tim,rout.tim as timeout,rin.dat
from reader rin
left join reader rout on rout.id=rin.id
    and rout.tim between '15:00:00' and '17:00:00'
    and rin.dat = rout.dat
where rin.tim between '09:00:00' and '14:00:00'
and rin.dat between '2011-01-17' and '2011-01-19' 
and rin.id =10704
union all
select rout.id,rin.tim,rout.tim as timeout,rout.dat
from reader rout
left join reader rin on rout.id=rin.id
    and rin.tim between '09:00:00' and '14:00:00'
    and rin.dat = rout.dat
where rout.tim between '15:00:00' and '17:00:00'
and rout.dat between '2011-01-17' and '2011-01-19' 
and rout.id =10704
and rout.id is null

这个特殊的UNION ALL表单模拟了MySQL中缺少的FULL JOIN。即使员工在任何一天进入但未离开或离开但未进入,您都可以看到数据。

答案 1 :(得分:1)

我认为如果你想要从一行中的一天分组来完成,那么将AND r1.dat=r2.dat添加到Thilo的代码可能会很有用。

答案 2 :(得分:0)

你应该能够以某种方式这样做: (我假设你有另一个字段提供信息,无论它是否进入。否则,你的查询基于一个非常弱的假设。但是:

SELECT r1.id, r1.tim, r2.tim, r1.dat 
FROM reader AS r1, reader AS r2 
WHERE r1.id = 10704 AND r2.id = 10704
    AND r1.tim BETWEEN '09:00:00' AND '14:00:00' 
    AND r2.tim BETWEEN '15:00:00' AND '17:00:00' 
    AND r1.dat BETWEEN '2011-01-17' AND '2011-01-19';

请注意,我将id的条件置于最顶端,假设它是最严格的条件,因此可能获得一点性能(查询优化器可能会在好的情况下单独执行)

干杯 蒂洛