1.计算年龄
如果你有一个人的生日而需要计算这个人的年龄,将下列语句中@dateofbirth替换为生日即可
代码如下 复制代码
select date_format (from_days (to_days (now ()) - to_days (@dateofbirth)), '%y') + 0;
2.计算两个日期的差值
计算两个日期的分,秒,小时和天数的差值,如果dt1和dt2的的格式是‘yyyy-mm-dd hh:mm:ss’,那么两个日期之间的秒数差值就是
代码如下 复制代码
unix_timestamp ( dt2 ) - unix_timestamp ( dt1 )
3.显示出现了n次的栏目的值
代码如下 复制代码
select id
from tbl
group by id
having count (*) = n;
4.计算两个日期之间的工作日
计算两个日期之间的工作日的最简单方法是是一个含有d日期栏目和另一个标定了在已知年份中所有日期是否为休息日的栏目的日历表,然后下面的查询就是找到在start和stop两个日期之间所有的工作日
代码如下 复制代码
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 ;
