来自多个表的SQL查询 - 连接不起作用

时间:2016-10-22 09:09:49

标签: sql sql-server

我尝试过子查询和连接查询,但我无法得到正确的答案,因为我需要从不同的表中检索数据。这就是我想要做的事情:

  

显示部门名称,街道地址和   城市的部门位置和国家名称   部门所在地的员工   名为Den Raphaely的名字

我有这样的桌子。

COUNTRIES TABLE

  • COUNTRY_ID
  • COUNTRY_NAME
  • 的region_id

DEPARTMENT TABLE

  • 部门标识
  • DEPARTMENT_NAME
  • MANAGER_ID
  • LOCATION_ID

员工表

  • 如first_name
  • 姓氏
  • 电子邮件
  • 电话
  • 薪水
  • 佣金
  • 部门标识
  • JOB_ID
  • HIRE_DATE

JOBS_HISTORY TABLE

  • EMPLOYEE_ID
  • 起始日期
  • END_DATE
  • JOB_ID
  • 部门标识

JOB TABLE

  • JOB_ID
  • Min_salary
  • MAX_SALARY

LOCATIONS TABLE

  • LOCATION_ID
  • STREET_ADDRESS
  • POSTAL_CODE
  • 国家
  • COUNTRY_ID

REGION TABLE

  • 的region_id
  • REGION_NAME

这是尝试过的查询

SELECT Employees.FIRST_NAME, Employees.LAST_NAME,
Departments.DEPARTMENT_NAME, Locations.Street_Address,
Locations.City, Countries.Country_Name FROM
Countries INNER JOIN Locations ON
Countries.Country_ID=Locations.Country_ID
INNER JOIN Departments ON
Locations.Location_id=Departments.LOCATION_ID
INNER JOIN Employees ON
Departments.DEPARTMENT_ID = (SELECT Employees.DEPARTMENT_ID FROM Employees
WHERE FIRST_NAME LIKE 'Den' AND LAST_NAME LIKE 'Raphaely')

2 个答案:

答案 0 :(得分:1)

您的JOIN与过滤(WHERE)逻辑混淆:

SELECT 
  Employees.FIRST_NAME, 
  Employees.LAST_NAME, 
  Departments.DEPARTMENT_NAME, 
  Locations.Street_Address, 
  Locations.City, 
  Countries.Country_Name 
FROM Countries 
   INNER JOIN Locations ON Countries.Country_ID=Locations.Country_ID
   INNER JOIN Departments ON Locations.Location_id=Departments.LOCATION_ID
   INNER JOIN Employees ON Departments.DEPARTMENT_ID = Employees.DEPARTMENT_ID
WHERE Employees.FIRST_NAME LIKE 'Den' AND Employees.LAST_NAME LIKE 'Raphaely'

答案 1 :(得分:0)

SELECT e.first_name, e.last_name, d.department_name, l.street_address, l.city, c.country_name
FROM
employees e
INNER JOIN
department d
ON e.department_id = d.department_id
INNER JOIN
location l
ON d.location_id = l.location_id
INNER JOIN country c
ON c.country_id = l.country_id
WHERE
e.first_name = 'Den'
AND
e.last_name = 'Raphaely'