请为我简化SQL查询

时间:2017-09-17 09:21:25

标签: mysql

  1. 我有一张员工的多个就业记录表,我想查询一定范围的日期。
  2. 参数为Company.id,date_hired,date_end
  3. 结果必须在指定日期的范围内,employee.id必须只有一个,如果员工有多个就业记录,结果必须得到最新的就业记录..
  4. 这就是我目前所拥有的。

    SELECT * 
      FROM employmentrecords 
     WHERE employmentrecords.id IN(
        SELECT MAX(employmentrecords.id) 
          FROM employmentrecords 
         WHERE ((employmentrecords.date_end >='2017-08-22' 
            OR employmentrecords.date_end IS NULL 
            OR (employmentrecords.date_end <='2017-08-22' 
            AND employmentrecords.date_end >='2017-08-08')) 
            AND employmentrecords.date_hired <='2017-08-22') 
         GROUP 
            BY employmentrecords.employee_id) 
           AND employmentrecords.company_id<>0`
    
    Hope any one would suggest a better approach.Thank you
    

2 个答案:

答案 0 :(得分:1)

我不确定我的问题是否清楚,如果有多个用户记录,下面的查询将为您提供最新的员工记录 -

destroy(req, res) {

    let id       = req.params.id;
    let language = {
        "code": req.body.code,
        "level": req.body.level
    };
    let type     = req.params.type;

    User.findOne({'_id': id}, function (err, user) {

        if (err) {
            return res.status(404).json({

                success: true,
                status: 404,
                data: err,
                message: "User does not exist",

            });
        }

        if (type === "teach") {

            for (let i = 0; i < user.languages.teach.length; i++)
                if (user.languages.teach[i].code === language.code) {
                    user.languages.teach[i].remove();
                    break;
                }

        }
        if (type === "learn") {
            //user.languages.learn.push(language);
        }

        console.log(user);

        user.save((err, user) => {

            return res.status(200).json({

                success: true,
                status: 201,
                data: user,
                message: "Successfully Deleted Language",

            });
        });

    });

}

JFYI,如果只有一个表从中获取数据,则不需要使用表名作为别名,这只会让你很难在去的时候读取查询。

答案 1 :(得分:1)

SELECT id, max(date_hired)
      FROM employmentrecords 
     WHERE ((employmentrecords.date_end >='2017-08-22' 
        OR employmentrecords.date_end IS NULL 
        OR (employmentrecords.date_end <='2017-08-22' 
        AND employmentrecords.date_end >='2017-08-08')) 
        AND employmentrecords.date_hired <='2017-08-22') group by id