分类 "MySQL" 下的文章

问题:远程连接mysql数据库时出现:SQL错误(2003)发生在语句 #0 can't connect to mysql server on...
mysql无法远程连接,但可以本地连接
补充:windows 10下出现10061错误,解决方法同下

解决:修改mysql配置,让它支持远程连接

方法:

  1. 在ubuntu服务器上locate my.cnf找到my.cnf文件
  2. 文件一般在mysql文件夹下(如果命令行安装的应该在/etc/mysql/下),vim my.cnf
    补充:在mysql Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu) 中bind-address在文件/etc/mysql/mysql.conf.d/mysqld.cnf中
  3. 将文件中bind-address修改完0.0.0.0
  4. 重启mysql服务 sudo service mysql restart

阅读全文

问题:使用mysql如何随机获取一条数据

解决:使用mysql自带的rand()方法

方法:
测试数据为4204641条数据,四百二十万记录(已经进行了数据表分表、并增加了user_id索引)

select count(1) from views;
受影响行数: 0  已找到记录: 1  警告: 0  持续时间 1 查询: 5.438 sec.

阅读全文

问题:sqlalchemy如何批量删除多条数据

解决:使用参数synchronize_session=False,或for循环

方法:

users = self.db.query(User).filter(User.id.in_(1,2,3)).all()
[self.db.delete(u) for u in users]
self.db.commit()

users = self.db.query(User).filter(User.id.in_(1,2,3)).delete(synchronize_session=False)
self.db.commit()

阅读全文

问题:使用sqlalchemy如何按月统计数据

解决:使用原生sql语句,使用sqlalchemy的execute方法

方法:

sks_months = self.db.execute("select month(end_time) as month
   , sum(used_time) as used_time from student_kejian_stats where
    student_id = %d and end_time > %s group by month" % (cuid, year))
    .fetchall()

select DATE_FORMAT(create_time,'%Y%m%d') days,count(caseid) count from tc_case group by days;
select DATE_FORMAT(create_time,'%Y%u') weeks,count(caseid) count from tc_case group by weeks;
select DATE_FORMAT(create_time,'%Y%m') months,count(caseid) count from tc_case group by months;

阅读全文

问题:mysql对日志表进行分区表操作时,想按时间进行range的,但是报错,如何解决?

表views
create talbe 'login_log' (
'id' int(10) unsigned not null primary key autoincrement,
'user_id' int(10) unsigned not null,
'login_time' datetime not null,
'login_ip' int(10) unsigned not null,
'login_type' tinyint(4) not null
) engine = innodb

分区表操作如下
alter table login_log partition by range(year(login_time)) (
    partition p2018 values less than (2019),
    partition p2019 values less than (2020),
    partition pmore values less than maxvalue
);

解决:需要将login_time也设置为主键,做成组合主键

阅读全文