mysql查询,嵌套where子句

时间:2012-04-07 14:21:44

标签: mysql arrays join left-join where-clause

我有一个工作查询,它​​计算表LDS中所有不同的值,其中STATUS ='OK'和DATE> ='2012'并且如果有多个相同的ID,则计算具有最新日期的ID,如果此id具有状态为“ok”:

COUNT(DISTINCT lds1.ID)
FROM 
    LDS lds1
    LEFT JOIN LDS lds2
        ON lds1.ID = lds2.ID
        AND lds1.Date < lds2.Date
        AND lds1.Status = 'ok'
WHERE 
    lds1.Date >= '2012'
    AND lds1.Status = 'ok'
    AND lds2.ID IS NUL 

我现在需要在运行上述查询之前将另一个条件添加为TRUE:“仅考虑其中STATUS = NULL AND DATE&gt; = 2011的ID”。在结果中不计入STATUS = NULL的初始ID实例;它只是确定是否应该考虑ID。

Table LDS:

ID | STATUS  | DATE
1  | NULL    | 2011
1  | ok      | 2012
2  | bad     | 2012
1  | bad     | 2013
3  | NULL    | 1999
3  | ok      | 2012
4  | ok      | 2012
5  | NULL    | 2011
5  | ok      | 2012
6  | NULL    | 2012

完整查询的预期结果是ID“5”。

更新:
也许这可以通过数组来解决?
1.从表LDS获取所有ID,其中STATUS = NULL AND DATE&gt; = 2011并放入数组(结果:ID1,ID5,ID6)
2.对于数组中的每个ID,检查表中的所有实例,并选择日期最大且STATUS IS NOT NULL的结果(结果:ID1,ID5)
3.计算其中有多少具有STATUS = OK(结果:ID5)

2 个答案:

答案 0 :(得分:0)

COUNT(DISTINCT lds1.ID)
FROM 
    LDS lds1
    LEFT JOIN LDS lds2
        ON (lds1.ID = lds2.ID)
    WHERE
        lds1.Date = '2012-01-01'
    AND lds1.Status = 'ok'
    AND lds2.ID IS NOT NULL 

尝试将where子句用于条件

答案 1 :(得分:0)

我相信我找到了答案。也许有人可以验证这一点。

COUNT DISTINCT ID 
FROM lds
    WHERE ID in 
( 
COUNT(DISTINCT lds1.ID)
FROM 
    LDS lds1
    LEFT JOIN LDS lds2
        ON lds1.ID = lds2.ID
        AND lds1.Date<lds2.Date
        AND lds1.Status = 'ok'
    WHERE 
        lds1.Date>='2012'
        AND lds1.Status = 'ok'
        AND lds2.ID IS NUL
)
AND DATE>='2011' AND STATUS=NUL