如何使用此选择创建动态WHERE?

时间:2011-06-15 17:07:47

标签: mysql sql tsql

您好我在下面选择此选项,它使用固定值以便于测试。

工作和删除的选择(中间选择)每个返回2组数据。

有没有办法动态获取这些中间选择的结果并使用它们在我的WHERE中添加BETWEENS?在纯粹的SQL?

我应该使用它们来制作where子句,以获得更高的选择。 中间选择的第一个值是gettin在我的正确位置但我丢失了他们每次获取的第二个,所以我的选择是返回模式数据然后预期。

    select b.bug_id, SUM(b.added) as rework
from    (select distinct b.bug_id, b.added, b.bug_when
        from bugs_activity as b, 
        (select b.bug_id,b.bug_when 
              from bugs_activity as b 
                  where b.bug_id = 13131 
                  and b.fieldid = 8 
                  and b.added like '%Rework%' 
               order by b.bug_when desc limit 500) as worked,
        (select b.bug_id,b.bug_when 
              from bugs_activity as b 
                  where b.bug_id = 13131 
                  and b.fieldid = 8 
                  and b.removed like '%Rework%' 
              order by bug_when desc limit 500) as removed        
        where b.bug_when between worked.bug_when and removed.bug_when
        and b.fieldid = 45
        and b.bug_id = worked.bug_id
        and b.bug_id = removed.bug_id
        and b.bug_id = 13131
        limit 500) as b
group by b.bug_id;

我需要在哪里成为这样的东西(working.bug_when3只是为了解释可以是任何东西)

where b.bug_when between worked.bug_when and removed.bug_when
or
b.bug_when between worked.bug_when2 and removed.bug_when2
or
b.bug_when between worked.bug_when3 and removed.bug_when3

2 个答案:

答案 0 :(得分:2)

HAVING对结果集中的计算值进行操作,并且可以与别名一起使用。

在你的情况下:

SELECT b.bug_id, SUM(b.added) AS rework
FROM
    ...
    LIMIT 500) as b
GROUP BY b.bug_id    
HAVING b.bug_when > 10 AND b.bug_when < 20;

您可能需要在顶部HAVINGSELECT)中选择SELECT b.bug_id, SUM(b.added) AS rework, b.bug_when所需的字段。

修改

有几个之间:

HAVING 
  (b.bug_when > 10 AND b.bug_when < 20) 
  OR (b.bug_when2 > 23 AND b.bug_when2 < 41) 
  OR (b.bug_when3 > 152 AND b.bug_when3 < 241)

答案 1 :(得分:1)

您是否测试了以下内容(使用子选择):

...
where b.bug_when between
    (select b.bug_when
    from bugs_activity as b
    where b.bug_id = 13131
    and b.fieldid = 8
    and b.added like '%Rework%'
    order by b.bug_when
    desc limit 1)
and
    (select b.bug_when
    from bugs_activity as b
    where b.bug_id = 13131
    and b.fieldid = 8
    and b.removed like '%Rework%'
    order by bug_when
    desc limit 1)
...

聚苯乙烯。你应该知道你应该避免使用subselects,想想...我相信事件发生两个单独的查询来获取这两个值然后将它们包含在查询中会比使用子选择更快...