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

      

  • 相关阅读:
    mysql整理-常用sql语句
    WAMP中的mysql设置密码
    cmd中输入net start mysql 提示:服务名无效或者MySQL正在启动 MySQL无法启动
    “laravel.log” could not be opened: failed to open stream
    RESTful API 设计指南
    理解RESTful架构
    PHP:API 接口规范完整版本
    php的api接口
    laravel5.5部署
    《面向对象程序设计》课程作业二
  • 原文地址:https://www.cnblogs.com/xiamaogeng/p/4453665.html
Copyright © 2011-2022 走看看