Mysql 常用 SQL 语句集锦

基础篇

1
2
//查询时间,友好提示
$sql = "select date_format(create_time, '%Y-%m-%d') as day from table_name";
1
2
//int 时间戳类型
$sql = "select from_unixtime(create_time, '%Y-%m-%d') as day from table_name";
1
2
3
4
5
//一个sql返回多个总数
select count(*) 全部,
count(case when ticketstatus = 2 then ticketstatus end) 已出票,
count(case when ticketstatus = 4 then ticketstatus end) 退款成功
from db_order.trainself_ticket
1
2
3
//替换某字段的内容的语句
$sql = "update table_name set content = REPLACE(content, 'aaa', 'bbb') ";
$sql .= " where (content like '%aaa%')";
1
2
//获取表中某字段包含某字符串的数据
$sql = "SELECT * FROM db_order.trainself_ticket WHERE LOCATE('杭州', departurestationname) ";
1
2
//获取字段中的前4位
$sql = "SELECT SUBSTRING(字段名,1,4) FROM 表名 ";
1
2
3
4
5
6
7
//查找表中多余的重复记录
//单个字段
$sql = "select * from 表名 where 字段名 in ";
$sql .= "(select 字段名 from 表名 group by 字段名 having count(字段名) > 1 )";
//多个字段
$sql = "select * from 表名 别名 where (别名.字段1,别名.字段2) in ";
$sql .= "(select 字段1,字段2 from 表名 group by 字段1,字段2 having count(*) > 1 )";
1
2
3
4
5
6
7
8
9
10
11
//删除表中多余的重复记录(留id最小)
//单个字段
$sql = "delete from 表名 where 字段名 in ";
$sql .= "(select 字段名 from 表名 group by 字段名 having count(字段名) > 1) ";
$sql .= "and 主键ID not in ";
$sql .= "(select min(主键ID) from 表名 group by 字段名 having count(字段名 )>1) ";
//多个字段
$sql = "delete from 表名 别名 where (别名.字段1,别名.字段2) in ";
$sql .= "(select 字段1,字段2 from 表名 group by 字段1,字段2 having count(*) > 1) ";
$sql .= "and 主键ID not in ";
$sql .= "(select min(主键ID) from 表名 group by 字段1,字段2 having count(*)>1) ";