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下使用git提交代码至GitHub
    C#几个小知识点
    C#中巧用#if DEBUG 进行调试
    使用 HPC Pack 为 Azure 中的 Windows HPC 工作负荷创建和管理群集的选项
    使用 Chef 自动执行 Azure 虚拟机部署
    在 Azure 中管理 Windows 虚拟机的可用性
    什么是 Azure 中的虚拟机规模集?
    从 Azure 下载 Windows VHD
    如何使用 Packer 在 Azure 中创建 Windows 虚拟机映像
  • 原文地址:https://www.cnblogs.com/xiamaogeng/p/4453665.html
Copyright © 2011-2022 走看看