分类 "MySQL" 下的文章

问题:mysql如何显示表字段编码,并修改
解决:使用sql语句操作
方法:
显示字段编码:SHOW FULL COLUMNS FROM tbl_name;
修改字段编码:

ALTER TABLE questions CHANGE info info TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

问题:使用mysql5.7的错误,因为mysql5.7默认开启了only_full_group_by模式
解决:select 中的字段必须全部在group by中
方法:
select max(users.id), max(users.name), users.age from users group by users.age;

对于GROUP BY聚合操作,如果在SELECT中的列,没有在GROUP BY中出现,那么这个SQL是不合法的,因为列不在GROUP BY从句中
所以对于设置了这个mode的数据库,在使用group by 的时候,就要用MAX(),SUM(),ANY_VALUE()这种聚合函数,才能完成GROUP BY 的聚合操作。

参考:http://blog.csdn.net/v587_lu/article/details/51785371

上面的方法能解决一部分问题,但还有的就不行了,此时可以使用临时表的方法:

select id, name,t.group_id, t.score from (select group_id, min(score) as score from game group by group_id order by min(score)) t inner join game on t.group_id=game.group_id and t.score=game.score

这样就能将表game按group_id进行分组之后找到score最小的用户id及name了

参考:http://blog.csdn.net/Allen_Tsang/article/details/54892046

问题:使用sqlalchemy如何更新json类型字段的数据
解决:获取json数据时虽然类型是dict,但仍需要进行dict()转换,否则无法更新
方法:

user = self.db.query(User).filter(
User.id == user_data['id']).first()
if not user:
info = {'country': user_data['country'],
'city': user_data['city']}
user = User(
nickname=user_data['nickname'],
info=info)
self.db.add(user)
else:
user.nickname=user_data['nickname']
info=dict(user.info)      # 注意这一步,不进行dict转换,就更新不成功
info['country']=user_data['country']
info['city']=user_data['city']
user.info=info
self.db.commit()

问题:a表的两个字段都对应b表的id,如何查询?
解决:将b表当两次用
方法:
select a.id, b.username as answer, c.username as owner  from forum_like as a, users as b, users as c  where a.answer_id=b.id and a.owner_id=c.id;