当前位置: 移动技术网 > IT编程>数据库>Mysql > MYSQL练习随笔

MYSQL练习随笔

2019年11月02日  | 移动技术网IT编程  | 我要评论

解法练习

 

案例1.子查询练习 

字段 说明
film_id 电影id
title 电影名称
description 电影描述信息
category_id 电影分类id
name 电影分类名称
last_update 电影分类最后更新时间
film_id 电影id
category_id 电影分类id
last_update 电影id和分类id对应关系的最后更新时间

ilm表
 
create table if not exists film (
film_id smallint(5)  not null default '0',
title varchar(255) not null,
description text,
primary key (film_id));
category表
 
create table category  (
category_id  tinyint(3)  not null ,
name  varchar(25) not null, `last_update` timestamp,
primary key ( category_id ));
film_category表
 
create table film_category  (
film_id  smallint(5)  not null,
category_id  tinyint(3)  not null, `last_update` timestamp);
 
使用子查询的方式找出属于action分类的所有电影对应的title,description
 
解题命令

 

select title,description
from film 
where film_id in(select film_id from film_category 
             where category_id in(select category_id from category w
                                 where name='action'))    
--子查询解法
select f.title,f.description
from film as f inner join film_category as fc on f.film_id = fc.film_id
               inner join category as c on c.category_id = fc.category_id
where c.name = 'action';
--常规解法

 

 

 

名词解释补充

explain解释

获取select * from employees对应的执行计划

explain select * from employees

连接字符串

将employees表的所有员工的last_name和first_name拼接起来作为name,中间以一个空格区分

--mysql、sql server、oracle等数据库支持concat方法,
而本题所用的sqlite数据库只支持用连接符号"||"来连接字符串
 
--concat方法:
select concat(concat(last_name," "),first_name) as name  from employees
--或者
select concat(last_name," ",first_name) as name  from employees
 
--本题中使用:
select last_name||" "||first_name as name  from employees

插入数据时,已有则忽略

insert ignore into ‘表’
values()

创建索引

create unique index ... on ... 创建唯一索引值
create index ... on ... 创建普通索引值
--例
create unique index uniq_idx_firstname on actor(first_name);
create index idx_lastname on actor(last_name);

mysql中常用的强制性操作

网址:

截取字符串

substr(字符串,起始位置,长度)
起始位置:截取的子串的起始位置(注意:字符串的第一个字符的索引是1)。值为正时从字符串开始位置 开始计数,值为负时从字符串结尾位置开始计数。
长度:截取子串的长度
--例 取first_name最后两位
select first_name from employees
order by substr(first_name,length(first_name)-1,2)
--mysql中的right函数
select first_name from employees order by right(first_name ,2);

 group_concat() 函数

group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc] [separator ‘分隔符’]
--分组后连接

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网