mysql常用语句六:DQL中的查询操作

1 创建唯一索引普通索引

表结构如下:

在这里插入图片描述

需求

first_name创建唯一索引uniq_idx_firstname,对last_name创建普通索引idx_lastname

SQL语句

create unique index uniq_idx_firstname on actor(first_name);
create index idx_lastname on actor(last_name);

2 转义符的使用

表结构如下

在这里插入图片描述

需求

将所有员工的last_namefirst_name通过'(单引号)连接起来。

SQL语句

select concat(last_name, '\'', first_name) as name from employees;
select concat(last_name, '''', first_name) as name from employees;
select concat(last_name, "'", first_name) as name from employees;

上面三个语句都是可以处理的。区别是对'的处理方式不同,常用的还是使用反斜杠转义\

运行结果

在这里插入图片描述

3 子查询`嵌套

表结构如下

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

需求

查找属于Action分类的所有电影对应的title,description

SQL语句

select title, description from film 
where film_id in (select film_id from film_category where category_id = 
 (select category_id from category where name = "Action"));

这里的查询涉及了3个表,titledescription只与film表有关,film_id则与category表film_category表有关,需要两重嵌套关系。

运行结果

在这里插入图片描述

4 插入记录,忽略重复项

表结构如下在这里插入图片描述

需求

对于表actor插入一条数据,如果数据已经存在,请忽略

actor_id first_name last_name last_update
‘3’ ‘ED’ ‘CHASE’ ‘2006-02-15 12:34:33’

SQL语句

insert ignore into actor values ('3', 'ED', 'CHASE', '2006-02-15 12:34:33');

使用了ignore关键词,避免了主键重复的问题

运行结果在这里插入图片描述

5 将查询结果作为记录插入到表中

表结构如下

表actor
在这里插入图片描述

表actor_name
在这里插入图片描述

需求

actor表中的所有first_name以及last_name导入actor_name表

SQL语句

insert into actor_name select first_name, last_name from actor;

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Awt_FuDongLai/article/details/114624543
今日推荐