zoukankan      html  css  js  c++  java
  • Mysql-两表的连接,copy表,select的各种用法

    -- 连接:外连接,内连接   两个表之间

    外连接:right join    left join

    -- left join  左标为主 一般以值少的为主
    select * from table1 left join table2 on table1.id = table2.id;
    
    -- right join  右标为主 一般以值少的为主
    select * from table1 right join table2 on table1.id = table2.id;

    内连接:join

    -- join 不给条件 相当于select * from table1,table2;  会产生笛卡儿积
    select * from table1 join table2 ;  
    
    -- join on +条件  一对一
    select * from table1 join table2 on table1.id=table2.id;

    Copy表

    -- 建新表是copy旧表数据
    -- 复制所有
    create table new select * from old;
    -- 将旧表的某些字段导入另一张表
    insert into new(字段1,23...) select 字段1,23... from old

    分组:group by

    -- 创建一个测试表
    create table test(
        id int primary key auto_increment,
        name varchar(15),
        age int
    );
    insert into test(name,age) values('tj',18),('th',15),('tr',10);
    
    --条件 查询
    -- select * from test;
    select * from test where age >12 && name = 'tj';
    select * from test where age >12 || name = 'tj';
    
    -- 取别名
    select name as '名字',age as '年龄' from test;  -- 取别名关键字as 可不写
    
    --查询行数
    -- limit
    select * from test limit 2;
    
    -- 当id 有自增长auto_increment,比如id 默认值到了5,删除了这五条数据,插入吓一跳数据id值默认+1成了6 
        -- truncate  可初始化自增长id 为1.
    
    -- 分组 group by
        --  几个字节对应几个分组字节
            select 字节1,字节2 from table group by 字节1,字节2.
    insert into test(name,age) values('tj1',18),('th1',15),('tr1',10);
    select age from test group by age;
    -- 分组+ 统计次数,最大值,最小值,和,平均值
    select age,count(*),max(age),min(age),sum(age),avg(age) from test 
    group by age;
    -- having +条件
    select age,count(*),max(age),min(age),sum(age),avg(age) from test 
    group by age having count(*)>=2;
    
    
    -- order by  排序 
    select * from test order by age;  -- 默认asc 升序
    select * from test order by age asc;     --等同上
    select * from test order by age desc;     -- 降序
     
  • 相关阅读:
    POJ 3660 Cow Contest (floyd求联通关系)
    POJ 3660 Cow Contest (最短路dijkstra)
    POJ 1860 Currency Exchange (bellman-ford判负环)
    POJ 3268 Silver Cow Party (最短路dijkstra)
    POJ 1679 The Unique MST (最小生成树)
    POJ 3026 Borg Maze (最小生成树)
    HDU 4891 The Great Pan (模拟)
    HDU 4950 Monster (水题)
    URAL 2040 Palindromes and Super Abilities 2 (回文自动机)
    URAL 2037 Richness of binary words (回文子串,找规律)
  • 原文地址:https://www.cnblogs.com/tangpg/p/8125482.html
Copyright © 2011-2022 走看看