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);
    

      

  • 相关阅读:
    [MacOS]Sublime text3 安装(一)
    [RHEL8]开启BBR
    PAT Advanced 1136 A Delayed Palindrome (20分)
    PAT Advanced 1144 The Missing Number (20分)
    PAT Advanced 1041 Be Unique (20分)
    PAT Advanced 1025 PAT Ranking (25分)
    PAT Advanced 1022 Digital Library (30分)
    PAT Advanced 1019 General Palindromic Number (20分)
    PAT Advanced 1011 World Cup Betting (20分)
    PAT Advanced 1102 Invert a Binary Tree (25分)
  • 原文地址:https://www.cnblogs.com/xiamaogeng/p/4453665.html
Copyright © 2011-2022 走看看