MySQL-子查询与连接

子查询
子查询是指出现在其他SQL语句内的SELECT子句。
例如:
select * from t1 where col1=(select col2 from t2);
其中select col2 from t2,称为子查询
子查询的外层查询可以是:select,insert,update,set或do。
使用比较运算符的子查询
=、>、<、>=、<=、<>、!=、<=>
SELECT ROUND(AVG(goods_price),2) from tdb_goods;  #求平均值,结果四舍五入保留2位小数
SELECT * from tdb_goods WHERE goods_price>=(SELECT ROUND(AVG(goods_price),2) from tdb_goods);
用ANY、SOME或ALL修饰的比较运算符

 

 SELECT * from tdb_goods WHERE goods_price>ANY(SELECT goods_price from tdb_goods WHERE goods_cate=‘笔记本‘);

使用[NOT]IN的子查询
语法结构
operand comparison_operator [NOT]IN (subquery)
=ANY 运算符与IN等效。
!=ALL或<>ALL运算符与NOT IN等效。

使用[NOT]EXISTS的子查询
如果子查询返回任何行,EXISTS将返回True;否则为False。
INSERT...SELECT
将查询结果写入数据表
insert [into] tal_name[(col_name,...)]
select...
INSERT INTO tdb_goods_cates(cate_name) SELECT goods_cate from tdb_goods GROUP BY goods_cate;
多表更新
update table_reference
set col_name1={expr1|DEFAULT}
[,col_name2={expr2|DEFAULT}]...
[where where_condition]
连接
MySQL在SELECT语句、多表更新、多表删除语句中支持JOIN操作。
语法结构
table_reference
{[INNER|CROSS]JOIN|{LEFT|RIGHT}[OUTER]JOIN}
table_reference
ON conditional_expr
连接类型
INNER JOIN,内连接
    在MySQL中,JOIN,CROSS JOIN和INNER JOIN是等价的。
LETF [OUTER] JOIN,左外连接
RIGHT [OUTER] JOIN,右外连接
UPDATE tdb_goods INNER JOIN tdb_goods_cates ON goods_cate=cate_name SET goods_cate=cate_id;
CREATE...SELECT
创建数据表同时将查询结果写入到数据表
CREATE TABLE [IF NOT EXISTS] tal_name
[(create_definition,...)]
select_statement
CREATE TABLE tdb_goods_brands(
brand_id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
brand_name VARCHAR(40) not NULL
)SELECT brand_name from tdb_goods GROUP BY brand_name;
UPDATE tdb_goods g INNER JOIN tdb_goods_brands b ON g.brand_name=b.brand_name SET g.brand_name=b.brand_id;
ALTER TABLE tdb_goods
CHANGE goods_cate cate_id SMALLINT UNSIGNED NOT NULL,
CHANGE brand_name brand_id SMALLINT UNSIGNED NOT NULL;

相关文章