子查询的ANY、SOME、ALL关键字及部分数据库查询操作技巧

1、第一种子查询(由比较运算符所引发的子查询)
这里写图片描述

eg:

select goods_id,goods_name,goods_price from tdb_goods where goods_price >all (select goods_price from tdb_goods where goods_cate='超极本');

2、第二种子查询(使用[not]in的子查询)
其中:
=any运算符与in等效。
!=all或<>all运算符与not in等效。

notice:
1、insert set 插入语句可以使用子查询(因为其中等号是典型的比较运算符),而 insert values 不能够使用子查询

2、查询语句如

```
select * from sometable \G;
```

可以获取具体的带分隔符的数据显示

3、将查询结果写入数据表

       insert [into] tal_name [(col_name,...)] select ...
           eg: insert into tdb_goods_cates(cate_name) select good_cate from tdb_goods group by goods_cate;

4、多表更新

update table_references set col_name1={expr1|default}[,col_name2={expr2|default}]...
[where where_condition]

如有商品表如下:
这里写图片描述
以及产品分类表如下:
这里写图片描述

需要实现将图一中goods_cate字段与图二中的cate_name实现连接更新表
则可以用以下代码实现:

update tdb_goods inner join tdb_goods_cates on goods_cate=cate_name set goods_cate=cate_id;

4、创建表并复制其他表中数据
eg:

create table tdb_goods_brands(
    brand id smallint unsigned primary key auto_increment,
    brand_name varchar(40) not null
)
select brand_name from tdb_goods group by brand_name;

若关联的两张表存在相同字段则会出现表含义模糊不清,无法完成更新,这种情况可以通过给表起别名,或在前面用表名.字段名来指明所操作的具体表。

eg:

update tdb_goods as g inner join tdb_goods_brands as b on g.brand_name=b.brand_name set g.brand_name =g.brand_id;  
发布了4 篇原创文章 · 获赞 0 · 访问量 1390

猜你喜欢

转载自blog.csdn.net/sumtre_w/article/details/53148844
今日推荐