用于匹配X位置中的N到Y位置中的M的字符的SQL查询

时间:2016-11-15 20:25:38

标签: sql sqlite

我试图弄清楚如何根据位置匹配字符,但我也希望子字符串匹配基于位置。

以下是我要做的事情:

    SELECT employee_table.LastFirst, employee_table.EmployeeId,
    MondayPlgReport.created_by,
        SUBSTR (employee_table.LastFirst, 0,5) AS employeeNameMatch
        SUBSTR (MondayPlgReport.created_by, 2,4) AS userNameMatch
    UPDATE MondayPlgReport
    SET MondayPlgReport.created_by=employee_table.EmployeeId
    WHERE employeeNameMatch=userNameMatch

我知道这很糟糕,但希望它澄清了我想要实现的目标。

我也尝试过:

    SELECT LastFirst, EmployeeId,
      SUBSTR (LastFirst, 0,5) AS employeeNameMatch
    FROM employee_table

    SELECT created_by,
      SUBSTR (created_by, 2,4) AS userNameMatch
    FROM MondayPlgReport

    UPDATE MondayPlgReport
    SET MondayPlgReport.created_by=employee_table.EmployeeId
    WHERE employeeNameMatch=userNameMatch

当我跑

    SELECT LastFirst, EmployeeId,
      SUBSTR (LastFirst, 0,5) AS employeeNameMatch
    FROM employee_table

或者

    SELECT created_by,
      SUBSTR (created_by, 2,4) AS userNameMatch
    FROM MondayPlgReport

然后我确实看到查询返回我正在寻找的结果。这里的问题是员工经常变动,我正在寻找另一个职位。如果每次有人离开或被雇用时都需要更新代码,那么一旦我离开,这对部门来说就没用了。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

如果您使用的是mysql,可以使用JOIN

UPDATE MondayPlgReport
JOIN mployee_table
SET MondayPlgReport.created_by=employee_table.EmployeeId
ON  SUBSTR(employee_table.LastFirst, 0,5)=SUBSTR(MondayPlgReport.created_by, 2,4)

和sqlite

UPDATE MondayPlgReport
SET created_by = (select  EmployeeId 
                  from  employee_table 
                  where  SUBSTR(LastFirst, 0,5) = SUBSTR(MondayPlgReport.created_by, 2,4));