如何在我的SQL脚本中将子查询添加为列?
e.g。
Select emp_no, name,gender ,
(select department_name from departments where employees.emp_no = departments.emp_no)
from employees
PS:我正在使用oracle 8
答案 0 :(得分:1)
按照语义,我理解的是,您希望员工的部门名称与他/她的其他信息一起显示。我建议你做一个加入:
Select emp_no, name, gender, department_name
from employees emp, departments dept
where emp.emp_no = dept.emp_no;
答案 1 :(得分:1)
看起来听起来合理,我建议清理一些(可能的拼写错误):在“性别”之后添加一个逗号并声明表名,同时设置子查询别名
Select employees.emp_no, employees.name, employees.gender,
(select departments.department_name from departments where employees.emp_no = departments.emp_no) as dept_name
from employees
或者,如果其他数据可行,那么一个好的连接也会起作用:
Select employees.emp_no, employees.name, employees.gender, departments.department_name
from employees
inner join departments on employees.emp_no = departments.emp_no
答案 2 :(得分:1)
left join
是最佳做法,应该在性能上更快:
Select e.emp_no, e.name, e.gender , d.department_name
from employees e left join departments d on e.emp_no = d.emp_no;
答案 3 :(得分:0)
你似乎在性别之后缺少逗号。
Select emp_no, name,gender ,
(select department_name from departments where employees.emp_no = departments.emp_no) as dept_name from employees
答案 4 :(得分:0)
以下是您的需求。只是在性别后添加了一个逗号。此子查询也需要为每个结果只返回一行,否则将看到错误。
Select emp_no, name,gender,
(select department_name from departments where employees.emp_no = departments.emp_no)
from employees
答案 5 :(得分:0)
此查询是您的答案,但只有在我们使用多个列而不是重新发送错误时才会提到一列时,它才会起作用。
"Select employee_id,first_name,
(select department_name,manager_id from departments where employees.department_id = departments.department_id) as new_column
from employees;"
答案 6 :(得分:0)
SELECT em.emp_no, em."name",em.gender ,
(SELECT
的不同强> dp.department_name
FROM departments dp
WHERE em.emp_no = dp.emp_no) my_sub
FROM employees em