简体   繁体   English

与sqlite中子查询的结果比较

[英]Comparison with results from sub-query in sqlite

Here is the code: 这是代码:

SELECT * FROM COMPANY WHERE SALARY > 40000;


4   Mark    25  Rich-Mond   65000.0
5   David   27  Texas       85000.0
6   Kim     22  South-Hall  45000.0
8   Kitos   31              90000.0

SELECT * FROM COMPANY 
        WHERE AGE < (SELECT AGE FROM COMPANY WHERE SALARY > 40000);

3   Teddy   23  Norway      20000.0
6   Kim     22  South-Hall  45000.0
7   James   24  Houston     10000.0

How does this work when there are multiple row returned from the sub-query? 当子查询返回多行时,该如何工作? In this example I would expect the last query to produce employees younger than 22 (minimum from the sub-query), apparently it doesn't work that way. 在此示例中,我希望最后一个查询产生的雇员小于22岁(子查询中的最小值),显然这行不通。

Most databases will raise an error if the subquery does not return exactly one result. 如果子查询未完全返回一个结果,则大多数数据库都会引发错误。 SQLite doesn't, but just uses the first returned row (or NULL) (there is an implied LIMIT 1 ). SQLite不会,但是只使用返回的第一行(或NULL)(隐含的LIMIT 1 )。 The order of SELECT results is not guaranteed without an ORDER BY, so the result will be random. 没有ORDER BY不能保证SELECT结果的顺序,因此结果将是随机的。

If you want to use some specific record, you must ensure that you SELECT returns exactly that record, typically using MIN/MAX, or with ORDER BY: 如果要使用某些特定记录,则必须确保SELECT准确返回该记录,通常使用MIN / MAX或ORDER BY:

SELECT ...
FROM Company
WHERE Age < (SELECT MIN(Age)
             FROM Company
             WHERE Salary > 40000);

SELECT ...
FROM Company
WHERE Age < (SELECT Age
             FROM Company
             WHERE Salary > 40000
             ORDER BY Age
             LIMIT 1);

It is also possible to use a correlated subquery , which can return a different result for each row in the outer query: 也可以使用相关子查询 ,该子查询可以为外部查询中的每一行返回不同的结果:

SELECT ...
FROM Company
WHERE Age < (SELECT Age
             FROM Company AS C2
             WHERE C2.ID = Company.ManagerID);

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

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