1.我想知道我们什么时候在select
子句中使用子查询的结构?
2.如果用 1. 结构编写的任何查询具有其他嵌套形式之一的等价物:
SELECT ... from ... where .. IN (SELECT ...)
SELECT ... from (SELECT ...)
谢谢
出于此答案的目的,我将第一个选择称为外部选择,第二个选择称为内部选择。
SELECT ... FROM ... WHERE ... IN (SELECT ...)
如果您想查找与您知道的记录相似的记录,您将使用。内部选择的项目可以与外部选择进行比较。
Get the population of cities which are in Texas
SELECT city, population FROM cities WHERE city IN (SELECT city FROM states WHERE state = 'Texas')
SELECT ... FROM ... (SELECT ...)
如果要为语句创建派生表,您将使用。然后可以在外部选择上使用在内部选择上计算的项目。
Get employees who have earned more than $500 this week (derived table x)
SELECT name, ROUND(wages) FROM (SELECT name, per_hour * hours_worked AS wages FROM timesheet) AS x WHERE wages > 500
还有第三种方式是相关子查询,SELECT ... FROM ... WHERE ... (= or > or < or != etc) (SELECT ...)
当您要根据计算选择行时,它将显示为并使用。
Get cities with bigger populations than 2 times the average
SELECT city, population FROM cities WHERE population > 2 * (SELECT AVG(population) FROM cities)