Oracle 5.0 Reference Manual page 1124

Table of Contents

Advertisement

Here is how to use a subquery in the
INSERT INTO t1 VALUES (1,'1',1.0);
INSERT INTO t1 VALUES (2,'2',2.0);
SELECT sb1,sb2,sb3
FROM (SELECT s1 AS sb1, s2 AS sb2, s3*2 AS sb3 FROM t1) AS sb
WHERE sb1 > 1;
Result:
2, '2',
4.0.
Here is another example: Suppose that you want to know the average of a set of sums for a grouped
table. This does not work:
SELECT AVG(SUM(column1)) FROM t1 GROUP BY column1;
However, this query provides the desired information:
SELECT AVG(sum_column1)
FROM (SELECT SUM(column1) AS sum_column1
FROM t1 GROUP BY column1) AS t1;
Notice that the column name used within the subquery (sum_column1) is recognized in the outer
query.
Subqueries in the
FROM
clause cannot be correlated subqueries, unless used within the
Subqueries in the
FROM
temporary tables are materialized). This occurs because upper-level queries need information about
all tables during the optimization phase, and the table represented by a subquery in the
unavailable unless the subquery is executed.
It is possible under certain circumstances to modify table data using
occur if the outer query accesses any tables and an inner query invokes a stored function that changes
one or more rows of a table. Suppose that there are two tables
shown here:
mysql>
CREATE DATABASE d1;
Query OK, 1 row affected (0.00 sec)
mysql>
USE d1;
Database changed
mysql>
CREATE TABLE t1 (c1 INT);
Query OK, 0 rows affected (0.15 sec)
mysql>
CREATE TABLE t2 (c1 INT);
Query OK, 0 rows affected (0.08 sec)
Now we create a stored function
mysql>
DELIMITER //
mysql>
CREATE FUNCTION f1(p1 INT) RETURNS INT
mysql>
BEGIN
mysql>
INSERT INTO t2 VALUES (p1);
mysql>
RETURN p1;
mysql>
END //
Query OK, 0 rows affected (0.01 sec)
mysql>
DELIMITER ;
Referencing the function directly in an
here:
mysql>
SELECT * FROM t2;
Empty set (0.00 sec)
Subquery Syntax
clause, using the example table:
FROM
clause can return a scalar, column, row, or table. Subqueries in the
clause are executed even for the
which modifies t2:
f1
EXPLAIN SELECT
1104
clause of a
ON
JOIN
statement (that is, derived
EXPLAIN
SELECT. This can
EXPLAIN
and
in database d1, created as
t1
t2
does not have any effect on t2, as shown
FROM
operation.
clause is
FROM

Advertisement

Table of Contents
loading

This manual is also suitable for:

Mysql 5.0

Table of Contents