简体   繁体   English

子查询实现

[英]Subquery implementation

I have a table employees我有一个表employees

------------------------------------------------
| name  | email              | date_employment |
|-------+--------------------|-----------------|
| MAX   | qwerty@gmail.com   | 2021-08-18      |
| ALEX  | qwerty2@gmail.com  | 1998-07-10      |
| ROBERT| qwerty3@gmail.com  | 2016-08-23      |
| JOHN  | qwerty4@gmail.com  | 2001-03-09      |
------------------------------------------------

and I want to write a subquery that will display employees who have been with them for more than 10 years.我想编写一个子查询来显示与他们一起工作超过 10 年的员工。

SELECT employees.name, employees.email, employees.date_employment
FROM employees
WHERE 10 > (SELECT round((julianday('now') - julianday(employees.date_employment)) / 365, 0) FROM employees);

After executing this request, it displays all employees, regardless of their seniority.执行此请求后,它会显示所有员工,无论其资历如何。 If you write a request like this, then everything works如果您编写这样的请求,那么一切正常

SELECT name, round((julianday('now') - julianday(employees.date_employment)) / 365, 0) as ex
FROM employees WHERE ex > 10;

Why subquery is not working properly?为什么子查询不能正常工作?

If you execute the subquery:如果执行子查询:

SELECT round((julianday('now') - julianday(employees.date_employment)) / 365, 0) AS ex
FROM employees

you will see that it returns 4 rows:你会看到它返回 4 行:

ex前任
1 1
24 24
6 6
21 21

It does not make sense to use the above resultset in a condition of a WHERE clause to compare it with 10.WHERE子句的条件中使用上述结果集与 10 进行比较是没有意义的。
But SQLite allows it, while other databases would throw an error.但是 SQLite 允许这样做,而其他数据库会抛出错误。

How does SQLite handle this case? SQLite 如何处理这种情况? It choses only 1 value of the resultset (usually the first ) and uses it in the WHERE clause, so your code is equivalent to:它只选择结果集的一个值(通常是第一个)并在WHERE子句中使用它,因此您的代码相当于:

WHERE 10 > 1

which is always true and this is why you get all the rows of the table as a result.这总是true ,这就是为什么你会得到表的所有行的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM