使用左连接从mysql表中获取非匹配行

时间:2013-09-26 07:53:23

标签: mysql

我的数据库中有一个步骤表。我想获取每个操作接下来要执行的所有步骤(每个步骤都附加到一个操作)。根据字段step_number(类型:十进制)依次执行步骤。条件如下

1-如果完成相同操作的上一步,则可以启动步骤。

2-属于相同操作且具有相同整数值的步骤,例如1.1和1.2可以同时运行

3-如果是操作的第一步,则启动它

SELECT 
        MIN(s1.step_number),
        s1.type,
        s1.operation,
        MAX(s2.step_number)
    FROM steps s1
    LEFT JOIN steps s2 
        ON  s1.operation = s2.operation
    WHERE 
        s1.state= 'not_started'
        AND s2.state != 'not_started'
        AND 
        (
            /* 1- A step can be started if previous step of same operation is completed. */
            (s2.state = 'confirmed')
            OR
            (
              /* 2- Steps belonging to same operation and having same integer value for e.g. 1.1 and 1.2 can run concurrently */
                s2.state != 'confirmed'
                AND CAST(s1.step_number AS UNSIGNED) = CAST(s2.step_number AS UNSIGNED)
            )
            OR
             /* 3- If its first step of the operation then start it */
            s1.step_number = (
                SELECT
                        MIN(step_number)
                    FROM steps s3
                    WHERE operation = s1.operation
                )
        )
    GROUP BY operation

查询不返回条件#3匹配的行,因为这些行已因左连接而被过滤掉。有没有另一种方法可以做到这一点,所以我可以获得所有三个条件的行。

0 个答案:

没有答案