我正在尝试为slq做一个简单的练习,我必须尽可能多地获取关于在我的数据库中在日本工作的人的信息。然而,我刚开始学习,所以我甚至不知道谷歌要回答我的问题。所以这就是:
我的代码:
SELECT *
FROM Employees
WHERE DEPARTMENT_ID =
(SELECT *
FROM Departments
WHERE LOCATION_ID =
(SELECT *
FROM Locations
WHERE Country_ID =
(SELECT *
FROM Countries
WHERE Country_Name = 'Japan')))
我的错误:
Msg 116, Level 16, State 1, Line 12
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 116, Level 16, State 1, Line 12
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 116, Level 16, State 1, Line 12
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
我的数据库: http://i.imgur.com/DOIFuBF.png
编辑:我想我碰壁了...... http://i.imgur.com/2Gd59nn.png答案 0 :(得分:3)
您在嵌套选择中使用select *
。您需要选择特定列。
这样的事情:
SELECT *
FROM Employees
WHERE DEPARTMENT_ID IN
(SELECT DEPARTMENT_ID
FROM Departments
WHERE LOCATION_ID IN
(SELECT LOCATION_ID
FROM Locations
WHERE Country_ID IN
(SELECT Country_ID
FROM Countries
WHERE Country_Name = 'Japan')))
使用JOINS
的相同查询是有效的。
SELECT *
FROM Employees
INNER JOIN Departments ON Employees.DEPARTMENT_ID = Departments.DEPARTMENT_ID
INNER JOIN Locations ON Departments.LOCATION_ID = Locations.Location_ID
INNER JOIN Countries ON Locations.Country_ID = Countries.Country_ID
WHERE Countries.Country_Name = 'Japan'
答案 1 :(得分:1)
您不能在IN语句中使用“SELECT *”。将您的查询更改为:
SELECT *
FROM Employees
WHERE DEPARTMENT_ID IN
(SELECT DEPARTMENT_ID
FROM Departments
WHERE LOCATION_ID =
(SELECT LOCATION_ID
FROM Locations
WHERE Country_ID =
(SELECT Country_ID
FROM Countries
WHERE Country_Name = 'Japan')))
答案 2 :(得分:0)
您需要在子查询上选择ID而不是*。你应该学会用这种方式编写它,这样你就知道如何使用子查询。但实际上对于这种类型的查询,您应该使用JOIN。以下是如何做到这一点的示例:
SELECT Employees.*
FROM Employees
INNER JOIN Departments
ON Employees.DEPARTMENT_ID = Departments.DEPARTMENT_ID
INNER JOIN Locations
ON Departments.LOCATION_ID = Locations.Location_ID
INNER JOIN Countries
ON Locations.Country_ID = Countries.Country_ID
WHERE Countries.Country_Name = 'Japan'
答案 3 :(得分:0)
我会用连接写它。更清洁。
SELECT e.*
FROM Employees e
JOIN Departments d ON e.Department_ID = d.id
JOIN Locations l ON d.location_id = l.id
JOIN Countries c ON l.country_id = c.id
WHERE c.Country_Name = 'Japan'