Mysql 常用語句實戰(1)

2022-09-09 08:03:11 字數 2552 閱讀 5304

用來建立表、插入資料

drop table if exists `emp`;

create table `emp` (

`id` int(11) not null comment '員工編號',

`name` varchar(255) character set utf8 collate utf8_general_ci null default null comment '員工姓名',

`dept_id` int(11) null default null comment '部門編號',

`leader` int(11) null default null comment '直屬領導id',

`is_enable` int(11) null default null comment '是否在職 1在職 0離職',

primary key (`id`) using btree

) engine = innodb character set = utf8 collate = utf8_general_ci row_format = compact;

insert into `emp` values (1, '張三丰', 1, 0, 1);

insert into `emp` values (2, '張無忌', 1, 1, 1);

insert into `emp` values (3, '小龍女', 1, 1, 1);

insert into `emp` values (4, '小白菜', 1, 3, 1);

insert into `emp` values (5, '韋小寶', 2, 0, 1);

insert into `emp` values (6, '令狐沖', 2, 0, 1);

insert into `emp` values (7, '東方不敗', 0, 8, 1);

insert into `emp` values (8, '任我行', 3, 0, 1);

insert into `emp` values (9, '李尋歡', 0, 8, 1);

drop table if exists `dept`;

create table `dept` (

`id` int(11) not null comment '部門id',

`name` varchar(255) character set utf8 collate utf8_general_ci null default null comment '部門名稱',

primary key (`id`) using btree

) engine = innodb character set = utf8 collate = utf8_general_ci row_format = compact;

insert into `dept` values (1, '銷售部');

insert into `dept` values (2, '資訊科技部');

insert into `dept` values (3, '財務部');

insert into `dept` values (4, '有關部門');

1、查詢張姓員工的員工資訊和所在部門資訊。

2、查詢張三丰管理了幾個員工

3、查詢出所有實習員工(實習員工無部門資訊)

4、查詢每個部門有多少個員工,並列印部門名字、部門裡的所有員工名字

-- 1、查詢張姓員工的員工資訊和所在部門資訊。

select t.username from

(select emp.id as id,emp.`name` as username,emp.dept_id,emp.leader,emp.is_enable,dp.`name` from emp inner join dept dp

on emp.dept_id = dp.id where emp.`name` like '%張%') t

-- 2、查詢張三丰管理了幾個員工

select count(*) from

(select e2.name as e2name from emp e1 inner join emp e2 on

e1. id = e2.leader where e1.`name` = "張三丰") t;

-- 3、查詢出所有實習員工(實習員工無部門資訊)

select count(*) from

(select * from emp e1 where e1.dept_idnot in(select id from dept)) t

-- 4、查詢每個部門有多少個員工,並列印部門名字、部門裡的所有員工名字//group_concat用於拼接字串,常與groupby在一起

select * from

(selectgroup_concat(e1.name) as username,dp.name as clname ,count(e1.name) from emp e1 right join dept dp on

e1.dept_id=dp.id group by dp.id) t

mysql常用語句 MySQL常用語句

create table student id int primary key auto increment comment 學號 name varchar 200 comment 姓名 age int comment 年齡 comment 學生資訊 修改表注釋 alter table studen...

php mysql 常用語句 mysql常用語句

一 修改mysql使用者密碼 mysql h localhost u root p 命令列登入 update user set password password 123456 where user root 二 資料庫操作 show databases 顯示資料庫 create database ...

Mysql常用語句部分 1

create database oa 建立資料庫 drop database oa 刪除資料庫 use oa 使用資料庫 alter table zhulei add column createtime timestamp default current timestamp 給表新增屬性 alter...