Subqueries
Sub-query is actually a one-time view is not stored in the hard disk. In the use of it as a general view can be operated.
Scalar query
Different from ordinary sub-queries return only a single data (line a), the only difference is, in fact, return scalar. That returns a scalar sub-query is called scalar query, can be used anywhere you can use a scalar.
For example, aggregate functions can not be used in the WHERE clause:
- error
SELECT product_id, product_name, sale_price
FROM Product
WHERE sale_price > AVG(sale_price);
- correct
SELECT product_id, product_name, sale_price
FROM Product
WHERE sale_price > (SELECT AVG(sale_price) FROM Product);
Correlated subquery
In short, there is no clear, so just to stick two pieces of code in order to understand its usage
- Select higher than average in the same commodity in commodity
SELECT product_type, product_name, sale_price
FROM Product AS P1
WHERE sale_price > (
SELECT AVG(sale_price) FROM Product AS P2
WHERE P1.product_type = P2.product_type
GROUP BY product_type
);
- Select the category of goods and where the average sale price
SELECT product_id,product_name,product_type,sale_price,
(SELECT AVG(sale_price) FROM Product AS P2 WHERE P1.product_type = P2.product_type GROUP BY product_type)
FROM Product AS P1;
Also note that this alias is also a scope. Variable Scope can refer to general programming language.
Also to be noted that some special SQL, such as Oracle can not be used AS
to define an alias.