zoukankan      html  css  js  c++  java
  • 数据库常用操作整理

    例子一:

    在数据库中往往有以下的统计操作,要统计某种类型的样本有多少个,并且找出大于500个样本的类型,以及拥有的样本数目。具体例子如,在SQL中,一个表的定义如下:

    CREATE TABLE t_account(
         account varchar(100),
         account_type TINYTEXT,
         PRIMARY KEY (account),
    };
    

    account为账号,account_type为该账号的类型,写出一个sql,统计账号数累计超过5000个账号类型,并显示对应的账号数,即结果中每行是(账号类型,账号数)

    select account_type, count(account) from t_account group by account_type having count(account)>5000;

    例子二:(Leetcode196: Delete Duplicate Emails)

    Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

    +----+------------------+
    | Id | Email            |
    +----+------------------+
    | 1  | john@example.com |
    | 2  | bob@example.com  |
    | 3  | john@example.com |
    +----+------------------+
    Id is the primary key column for this table.
    

    For example, after running your query, the above Person table should have the following rows:

    +----+------------------+
    | Id | Email            |
    +----+------------------+
    | 1  | john@example.com |
    | 2  | bob@example.com  |
    +----+------------------+

    找到要保留的数据 然后用not in 来删除不再这些数据中的记录。大家很容易就想到如下的sql语句:

    delete from Person where Id not in (select * from (select min(Id) from Person group by Email));
    

      但是mysql删  除动作不能带有本表的查询动作,意思是你删除users表的东西不能以Person表的信息为条件 所以这个语句会报错,执行不了。只要通过创建临时表作为查询条件。具体实现如下:

    delete from Person where Id not in (select * from (select min(Id) from Person group by Email) as w);
    

      

  • 相关阅读:
    ubuntu 安装docker
    docker 版本与查看某个容器详情信息
    linux namespace 分为有名和无名两种,默认情况下都是有名的
    查看centos 版本信息
    centos7 一键安装openstack 方法
    centos8 安装openstack (失败告终),参见centos7安装
    Windows7 安装docker工具的方法
    网络架构--防火墙双机热备(主备、负载均衡)
    ubuntu server 无线网口配置
    ubuntu server 18.04 单机安装openstack
  • 原文地址:https://www.cnblogs.com/xiamaogeng/p/4453665.html
Copyright © 2011-2022 走看看