=》子查询或内部查询或嵌套查询在另一个SQL查询的查询和嵌入式WHERE子句中。
=》子查询用于返回将被用于在主查询作为条件的数据,以进一步限制要检索的数据。
=》子查询可以在SELECT,INSERT,UPDATE使用,而且随着运算符如DELETE语句 =, <, >, >=, <=, IN, BETWEEN 等.
子查询最频繁使用的SELECT语句。其基本语法如下:
SELECT column_name [, column_name ]FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE])
#例子
SQL> SELECT * FROM CUSTOMERS WHERE ID IN
(SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ;
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ]
#例子
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS) ;
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
#例子
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
#例子
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE > 27 );
递增
使用自动递增(AUTO_INCREMENT)列:
在MySQL中最简单的方法来使用顺序是定义一个列AUTOINCREMENT并保留其余的事情由MySQL处理。
mysql> CREATE TABLE INSECT
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO INSECT (id,name,date,origin) VALUES
-> (NULL,'housefly','2001-09-10','kitchen'),
-> (NULL,'millipede','2001-09-10','driveway'),
-> (NULL,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM INSECT ORDER BY id;
+----+-------------+------------+------------+
| id | name | date | origin |
+----+-------------+------------+------------+
| 1 | housefly | 2001-09-10 | kitchen |
| 2 | millipede | 2001-09-10 | driveway |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)
设置初始序列
mysql> CREATE TABLE INSECT
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
#或者
mysql> ALTER TABLE t AUTO_INCREMENT = 100;
重编一个现有的序列:
有可能出现一种情况,当从表中已删除多条记录,并且希望所有的记录重新排序。这可以通过使用一个简单的技巧来完成,但这样做要非常小心,如果你的表连接使用其他表。
如果确定重新排序AUTO_INCREMENT列是不可避免的,这样做的方式是从表中删除列,然后重新添加这个删除的列。下面的例子演示了如何使用这种技术在 insect 表重新编号ID值:
mysql> ALTER TABLE INSECT DROP id;
mysql> ALTER TABLE insect
-> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
-> ADD PRIMARY KEY (id);