SELECT,FROM或WHERE中的嵌套SELECT子句和差异

时间:2013-02-25 08:36:39

标签: mysql sql tsql

1.我想知道我们何时在select子句中使用子查询的结构?

2.如果以1.结构编写的任何查询在其他嵌套表单中具有等效内容:

  SELECT ... from ... where .. IN (SELECT ...)
    SELECT ... from (SELECT ...)

由于

1 个答案:

答案 0 :(得分:4)

出于本答案的目的,我将第一个选择称为外部选择,第二个选择作为内部选择。

如果要查找与您了解的记录类似的记录,则可以使用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)