问题: 我有下表和数据设置:
CREATE TABLE EMPLOYEE (
empId INTEGER AUTO_INCREMENT PRIMARY KEY,
name TEXT NOT NULL,
dept TEXT NOT NULL
);
INSERT INTO EMPLOYEE(name, dept) VALUES ('Clark', 'Sales');
INSERT INTO EMPLOYEE(name, dept) VALUES ('Dave', 'Accounting');
INSERT INTO EMPLOYEE(name, dept) VALUES ('Ava', 'Sales');
我正在运行此查询:
SELECT *
FROM EMPLOYEE AS a
INNER JOIN EMPLOYEE b
ON a.empId = (SELECT MIN(b.empId));
输出:
+-------+-------+------------+-------+-------+------------+
| empId | name | dept | empId | name | dept |
+-------+-------+------------+-------+-------+------------+
| 1 | Clark | Sales | 1 | Clark | Sales |
| 2 | Dave | Accounting | 2 | Dave | Accounting |
| 3 | Ava | Sales | 3 | Ava | Sales |
+-------+-------+------------+-------+-------+------------+
我希望查询仅返回 empId = 1 的行,但它返回所有行。有人可以解释为什么会发生这种情况以及 INNER JOIN 如何使用子查询评估 ON 子句吗?
这里正确的行为是什么?如何修复此问题以仅获取具有最小 empId 的行?
SQL 连接需要直接链接两个表“a”和“b”的列,然后可以通过添加其他过滤器来进一步限制行,例如
SELECT *
FROM EMPLOYEE AS a
INNER JOIN EMPLOYEE b
ON a.empId = b.empId
AND a.empId = (SELECT MIN(empId) FROM EMPLOYEE);
输出:
1 Clark Sales 1 Clark Sales
子查询首先由DMS处理,并且不能引用外表。