SQL查询未按预期工作|重复和错误的结果

时间:2014-09-28 20:39:18

标签: mysql sql

HEyo人。

好吧,所以我正在处理这段代码

        SELECT 
                current.name, 
                current.status, 
                current.votes,
                current.info, 
                current.votes_required, 
                current.sid as sid,
                current.previous_required,
                previous.sid as psid,
                previous.status as status
            FROM
                systems as current
            INNER JOIN
                systems as previous
            WHERE
                (previous.status = 1 and current.previous_required = previous.status)
                OR
                (current.previous_required = 0)
            '

理想情况下,我想在previous_required == 0或previous_required状态== 1的情况下显示结果。但是,出于某种原因,我保持从搜索结果中获得三倍(EG重复)或仅单个结果为第一个。

我非常确定我知道我在哪里弄乱(这是内部加入或OR声明)。但我似乎无法确定下来并解决问题。任何意见都将不胜感激。

2 个答案:

答案 0 :(得分:0)

看起来您需要以某种方式将当前记录链接到以前的记录。您的系统表是否具有" previous_sid"之类的内容,它将当前记录链接回前一个记录?如果是这样,您需要在内部联接中使用它。类似的东西:

FROM 
    systems AS current
INNER JOIN
    systems AS previous on current.previous_sid = previous.sid

答案 1 :(得分:0)

您需要移动条件从何处加入

    SELECT 
            current.name, 
            current.status, 
            current.votes,
            current.info, 
            current.votes_required, 
            current.sid as sid,
            current.previous_required,
            previous.sid as psid,
            previous.status as status
        FROM
            systems as current
        INNER JOIN
            systems as previous
          ON
            (previous.status = 1 and current.previous_required = previous.status)
            OR
            (current.previous_required = 0)