mysql query, nested where clauses

北战南征 提交于 2019-12-12 05:19:54

问题


I have a working query that counts all distinct values from table LDS where STATUS = 'OK' AND DATE >= '2012' AND if there are multiple identical IDs then count the one with the newest date if this id has a status of "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 

I now need to add another condition to be TRUE before the above query is run: "only consider IDs where STATUS=NULL AND DATE>= 2011". The initial ID instance with STATUS = NULL is not to be counted in the results; it just determines if an ID should even be considered.

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

The expected result of the full query is ID "5".

UPDATE:
Maybe this can be solved with arrays?
1. take all IDs from table LDS where STATUS=NULL AND DATE>=2011 and put into array (result: ID1, ID5, ID6)
2. For each ID in the array, check all instances in the table and select the one with the largest date AND STATUS IS NOT NULL (result: ID1, ID5)
3. Count how many of these have a STATUS=OK (result: ID5)


回答1:


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 

try to use where clause for conditions




回答2:


I believe I have found an answer. Maybe someone could verify this.

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 


来源:https://stackoverflow.com/questions/10055244/mysql-query-nested-where-clauses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!