MySql multi-table queries and data import

Senior MySQL

Foreign key (foreign key)

  • definition

    Let the value of the current table field is selected in the range of another table

  • grammar

    foreign key(参考字段名)
    references 主表(被参考字段名)
    on delete 级联动作
    on update 级联动作
  • Use Rules

1, the main table, the data type to be consistent Field
2, the main reference field table is: KEY one kind, usually a primary key

  • Examples

Table 1, payment information table (Finance)

id   姓名     班级     缴费金额
1   唐伯虎   AID19     300
2   点秋香   AID19     300
3   祝枝山   AID19     300
create table master(
    -> id int primary key,
    -> name varchar(20),
    -> class char(5),
    -> money decimal(6,2)
    -> )charset=utf8;

Table 2, student information table (teacher) - do foreign key

stu_id   姓名   缴费金额
  1     唐伯虎    300
  2     点秋香    300
create table slave(
    -> stu_id int,
    -> name varchar(20),
    -> money decimal(6,2),
    -> foreign key(stu_id) references master(id) on delete cascade on update cascade)
    -> charset=utf8;
  • Remove the foreign key **
alter table 表名 drop foreign key 外键名;
​外键名 :show create table 表名;
  • Cascade action
cascade
​数据级联删除、更新(参考字段)
create table slave(
    -> stu_id int,
    -> name varchar(20),
    -> money decimal(6,2),
    -> foreign key(stu_id) references master(id) on delete cascade on update cascade)
    -> charset=utf8;

restrict(默认)
​从表有相关联记录,不允许主表操作
create table slave_2 (stu_id int,
    -> name varchar(20),
    -> money decimal(6,2),
    -> foreign key(stu_id) references master(id) on delete restrict on update restrict)
    -> charset = utf8;

set null
​主表删除、更新,从表相关联记录字段值为NULL
create table slave_3(stu_id int,
    name varchar(20),
    money decimal(6,2),
    foreign key (stu_id) references master(id) on delete set null on update set null)
    charset=utf8;
  • Add an existing table a foreign key
alter table 表名 add foreign key(参考字段) references 主表(被参考字段) on delete 级联动作 on update 级联动作

Nested queries (subqueries)

definition

The query result as the outer layer of the inner query

Syntax

select ... from 表名 where 条件(select ....);

Examples

1、把攻击值小于平均攻击值的英雄名字和攻击值显示出来
        select name,attack from sanguo where attack <(select avg(attack)from country);
2、找出每个国家攻击力最高的英雄的名字和攻击值(子查询)
        select name,attack from sanguo where (attack,country) in (select country ,max(attack)from sanguo group by country);
 

Multi-table query

sql script information: join_query.sql, or copy the code below

mysql -uroot -p123456
mysql>source /home/tarena/join_query.sql
create database if not exists db1 character set utf8;
use db1;

create table if not exists province(
id int primary key auto_increment,
pid int,
pname varchar(15)
)default charset=utf8;

insert into province values
(1, 130000, '河北省'),
(2, 140000, '陕西省'),
(3, 150000, '四川省'),
(4, 160000, '广东省'),
(5, 170000, '山东省'),
(6, 180000, '湖北省'),
(7, 190000, '河南省'),
(8, 200000, '海南省'),
(9, 200001, '云南省'),
(10,200002,'山西省');

create table if not exists city(
id int primary key auto_increment,
cid int,
cname varchar(15),
cp_id int
)default charset=utf8;

insert into city values
(1, 131100, '石家庄市', 130000),
(2, 131101, '沧州市', 130000),
(3, 131102, '廊坊市', 130000),
(4, 131103, '西安市', 140000),
(5, 131104, '成都市', 150000),
(6, 131105, '重庆市', 150000),
(7, 131106, '广州市', 160000),
(8, 131107, '济南市', 170000),
(9, 131108, '武汉市', 180000),
(10,131109, '郑州市', 190000),
(11,131110, '北京市', 320000),
(12,131111, '天津市', 320000),
(13,131112, '上海市', 320000),
(14,131113, '哈尔滨', 320001),
(15,131114, '雄安新区', 320002);

create table if not exists county(
id int primary key auto_increment,
coid int,
coname varchar(15),
copid int
)default charset=utf8;

insert into county values
(1, 132100, '正定县', 131100),
(2, 132102, '浦东新区', 131112),
(3, 132103, '武昌区', 131108),
(4, 132104, '哈哈', 131115),
(5, 132105, '安新县', 131114),
(6, 132106, '容城县', 131114),
(7, 132107, '雄县', 131114),
(8, 132108, '嘎嘎', 131115);
  • Cartesian product (cross-connect)
select 字段名列表 from 表名列表; 
  • Multi-table query
select 字段名列表 from 表名列表 where 条件;
  • Examples
1、显示省和市的详细信息
   河北省  石家庄市
   河北省  廊坊市
   湖北省  武汉市
    select province.pname,city.cname from province,city where province.pid=city.cp_id;
2、显示 省 市 县 详细信息
        select province.pname,city.cname,county.coname from province,city,county 
        where province.pid=city.cp_id and city.cp_id=county.copid;

Join query

  • The connector (result of a query with multiple tables, to display the matching records)
select 字段名 from  表1 inner join 表2 on 条件 inner join 表3 on 条件;
eg1 : 显示省市详细信息
            select province.pname,city.cname from province inner join city on province.pid=city.cp_id;

eg2 : 显示 省 市 县 详细信息
            select province.pname,city.cname,county.coname from 
            province inner join city on province.pid=city.cp_id inner join county on city.cp_id=county.copid;
  • Left outer join

Table to the left of the main display query results

select 字段名 from 表1 left join 表2 on 条件 left join 表3 on 条件;
eg1 : 显示 省 市 详细信息(要求省全部显示)
            select province.pname,city.cname from province left join city on province.pid=city.cp_id;
  • Right outer join

Usage connected with the left, the main query results are displayed to the right table

select 字段名 from 表1 right join 表2 on 条件 right join 表3 on 条件;
        select province.pname,city.cname from province right join city on province.pid=city.cp_id;

data import

== == grasp the general steps

.Sql == == source file name

effect

The contents of the file system imported into the database
syntax (Mode 1)

load data infile "filename"
INTO table name Table
fields terminated by "delimiter"
Lines terminated by "\ n-"
exemplary
scoretable.csv file into a table in database db2

1、将scoretable.csv放到数据库搜索路径中
   mysql>show variables like 'secure_file_priv';
         /var/lib/mysql-files/
   Linux: sudo cp /home/tarena/scoreTable.csv /var/lib/mysql-files/
2、在数据库中创建对应的表
  create table scoretab(
  rank int,
  name varchar(20),
  score float(5,2),
  phone char(11),
  class char(7)
  )charset=utf8;
3、执行数据导入语句
load data infile '/var/lib/mysql-files/scoreTable.csv'
into table scoretab
fields terminated by ','
lines terminated by '\n'
4、练习
  添加id字段,要求主键自增长,显示宽度为3,位数不够用0填充
  alter table scoretab add id int(3) zerofill primary key auto_increment first;

Syntax (second approach)

source file name .sql

Data output

effect

Save the record to the system tables in the database file

Syntax

select ... from the table name
into outfile "file name"
Fields terminated by "separator"
Lines terminated by "separator";

Exercise

1、把sanguo表中英雄的姓名、攻击值和国家三个字段导出来,放到 sanguo.csv中
        select name,attack,country from sanguo 
        into outfile '/var/lib/mysql-files/sanguo.csv' 
        fields terminated by ',' 
        lines terminated by '\n';
2、将mysql库下的user表中的 user、host两个字段的值导出到 user2.txt,将其存放在数据库目录下
        select user,host from country 
        into outfile '/var/lib/mysql-files/user2.txt' 
        fields terminated by ',' 
        lines terminated by '\n';
 

note

1、导出的内容由SQL查询语句决定
2、执行导出命令时路径必须指定在对应的数据库目录下

Copy the table

== 1, the table can copy data according to the actual needs ==

== 2, does not copy over == KEY attribute copy table

grammar

create table 表名 select 查询命令;

Exercise

1、复制sanguo表的全部记录和字段,sanguo2
        create table sanguo2 select * from country.sanguo
        
2、复制sanguo表的 id,name,country 三个字段的前3条记录,sanguo4
        create table sanguo4 select id,name,country from country.sanguo limit 3;
        

note

Extended Share

Conventional sub-table routine:

User ID: int% Table Number

Username: ASCII% table quantities

Classic case: the user table points table

Copy the table when the property does not copy over the original table KEY

Copy table structure
create table table name select query where false;

Lock (automatic locking and releasing locks)

== full focus lock theory and classification and characteristics ==

purpose

Resolve conflicts clients concurrent access

Lock type classification

读锁(共享锁):select 加读锁之后别人不能更改表记录,但可以进行查询
写锁(互斥锁、排他锁):加写锁之后别人不能查、不能改

Lock granularity classification

Table-level lock: myisam
row-level locking: innodb

Guess you like

Origin www.cnblogs.com/-xiaolong/p/11477864.html