• 有用的MySQL语句


    摘自onefish资料库

    1. 计算年数
    你想通过生日来计算这个人有几岁了。

    SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofbirth)), '%Y') + 0; 

    2. 两个时间的差
    取得两个 datetime 值的差。假设 dt1 和 dt2 是 datetime 类型,其格式为 ‘yyyy-mm-dd hh:mm:ss’,那么它们之间所差的秒数为:

     UNIX_TIMESTAMP( dt2 ) - UNIX_TIMESTAMP( dt1 )

    除以60就是所差的分钟数,除以3600就是所差的小时数,再除以24就是所差的天数。

    3. 显示某一列出现过N次的值

    SELECT id
    FROM tbl
    GROUP BY id
    HAVING COUNT(*) = N;
     

    4. 计算两个日子间的工作日
    所谓工作日就是除出周六周日和节假日。

    SELECT COUNT(*)
    FROM calendar
    WHERE d BETWEEN Start AND Stop
      AND DAYOFWEEK(d) NOT IN(1,7)
      AND holiday=0;

    5. 查找表中的主键

     SELECT k.column_name
    FROM information_schema.table_constraints t
    JOIN information_schema.key_column_usage k
    USING (constraint_name,table_schema,table_name)
    WHERE t.constraint_type='PRIMARY KEY'
      AND t.table_schema='db'
      AND t.table_name=tbl'

     

    6. 查看你的数库有多大

     SELECT
      table_schema AS 'Db Name',
      Round( Sum( data_length + index_length ) / 1024 / 1024, 3 ) AS 'Db Size (MB)',
      Round( Sum( data_free ) / 1024 / 1024, 3 ) AS 'Free Space (MB)'
    FROM information_schema.tables
    GROUP BY table_schema ;

    7.当你想要用字符串当成数字类型作为order by的字段时

      

    SELECT * FROM `uchome_plug_collect_in` WHERE `collectid` = 4744346 ORDER BY CAST(unote AS SIGNED) DESC
    SELECT * FROM `uchome_plug_collect_in` WHERE `collectid` = 4744346 ORDER BY `unote`+0 DESC
    

    8.查询数据大小

    SELECT CONCAT( ROUND( ( INDEX_LENGTH + DATA_LENGTH ) /1024 /1024, 2 ) , 'MB' ) AS '总大小', CONCAT( ROUND( DATA_LENGTH /1024 /1024, 2 ) , 'MB' ) AS '数据大小', CONCAT( ROUND( INDEX_LENGTH /1024 /1024, 2 ) , 'MB' ) AS '索引大小' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '数据库名' AND TABLE_NAME = '表名'
    

      

  • 相关阅读:
    轻松自动化---selenium-webdriver(python) (八)
    Ubuntu 18.04 LTS 启用 WakeOnLAN
    lower_bound 和 upper_bound
    [LeetCode 201.] Bitwise AND of Numbers Range
    [LeetCode 162.] Find Peak Element
    [LeetCode 33. 81. 153. 154.] 旋转数组中的二分查找
    C++ unordered_map 的一个疑问
    [LintCode 386.] 最多有k个不同字符的最长子字符串
    [LintCode 550.] 最常使用的K个单词II
    [LintCode 1029.] 寻找最便宜的航行旅途(最多经过k个中转站)
  • 原文地址:https://www.cnblogs.com/yingnan/p/4716576.html
Copyright © 2020-2023  润新知