如何修复“ 1054-子句中的未知列”

时间:2019-02-19 07:50:37

标签: mysql sql

我写了一个SQL代码来从MySQL数据库中获取数据。但是当我运行sql查询时,它返回错误。

我该如何解决。我对此很陌生,我用谷歌搜索,但找不到解决方法。

  

1054-“ on子句”中的未知列“ departments.department_id”

SELECT
    staff_data.first_name,
    staff_data.middle_name,
    staff_data.last_name,
    staff_data.gender,
    staff_data.civil_status,
    staff_data.birthday,
    staff_data.address_line_1,
    staff_data.address_line_2,
    staff_data.address_line_3,
    staff_data.contact_no_1,
    staff_data.contact_no_2,
    staff_data.nationality,
    staff_data.religion,
    staff_data.email,
    staff_data.is_deleted,
    staff_data.nic_number,
    staff_data.is_admin,
    departments.department_name,
    job_positions.position_name 
FROM
    departments,
    employee_position
    INNER JOIN job_positions ON job_positions.department_id = 
departments.department_id 
    AND departments.department_id = job_positions.department_id 
    AND employee_position.position_id = job_positions.position_id
    INNER JOIN staff_data ON employee_position.user_id = 
staff_data.nic_number 
WHERE
    employee_position.is_valid = 1

2 个答案:

答案 0 :(得分:2)

请勿将老式的联接语法与现代语法(您仅应使用后者)混合使用。这是使用现代联接语法的更正查询:

SELECT
    s.first_name,
    s.middle_name,
    s.last_name,
    s.gender,
    s.civil_status,
    s.birthday,
    s.address_line_1,
    s.address_line_2,
    s.address_line_3,
    s.contact_no_1,
    s.contact_no_2,
    s.nationality,
    s.religion,
    s.email,
    s.is_deleted,
    s.nic_number,
    s.is_admin,
    d.department_name,
    j.position_name 
FROM departments d
INNER JOIN job_positions j
    ON j.department_id = d.department_id 
INNER JOIN employee_position e
    ON e.position_id = j.position_id
INNER JOIN staff_data s
    ON e.user_id = s.nic_number
WHERE
    e.is_valid = 1;

您看到的错误可能是由于您使用旧式联接语法而使MySQL解析器进入某种模式的事实,这种行为随后不会像您期望的那样起作用。

请注意,我还引入了表别名,这使查询更易于阅读。

答案 1 :(得分:0)

问题与第一次加入

SELECT
    staff_data.first_name,
    staff_data.middle_name,
    staff_data.last_name,
    staff_data.gender,
    staff_data.civil_status,
    staff_data.birthday,
    staff_data.address_line_1,
    staff_data.address_line_2,
    staff_data.address_line_3,
    staff_data.contact_no_1,
    staff_data.contact_no_2,
    staff_data.nationality,
    staff_data.religion,
    staff_data.email,
    staff_data.is_deleted,
    staff_data.nic_number,
    staff_data.is_admin,
    departments.department_name,
    job_positions.position_name 
FROM
    departments,
    employee_position
    INNER JOIN job_positions ON 
    job_positions.department_id = <change to req col>
    -- departments.department_id join between employee_position and job_positions, but join is on department table 
    AND departments.department_id = job_positions.department_id 
    AND employee_position.position_id = job_positions.position_id
    INNER JOIN staff_data ON employee_position.user_id = 
staff_data.nic_number 
WHERE
    employee_position.is_valid = 1