C#操作MySQL的问题和SQL统计去重问题
kelvin 发布于 2021-07-21

1、MySQL查询语句中的统计字段,例如使用count函数返回一个个数统计的字段,在反射到C#实体类的时候对应的是Int64类型,一开始不知道,以为默认是int类型,结果反射的时候报错了,

Object of type 'System.Int64' cannot be converted to type 'System.Int32

所以实体类的对应字段干脆设置为Int64

2、Id字段设置一些思考,有些人喜欢设置为int或者bigint,有些人喜欢使用uuid(guid)——对应char(32或者36位),但如果有统计去重,使用group by的考虑时候,建议使用int类型,因为group by 后面的字段和select的字段要对应,例如group by col1,col2, select col1,col2,max(colN)查出其他字段,不能直接select col3,在SQLyog中调试发现也可以,但是如果在C#中调用,也会报错

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db.m.Id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db.a.Photo' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

有些解决方案说要设置MySQL的配置文件,但是考虑到这种方式不是在代码里面解决,还是放弃了。

所以如果id是int类型的话,可以先group by 在select中max(Id),然后在外层使用join语句在查询一次,根据id在关联出来,就可以既统计又查询其他字段。这也是很多人问的在查询中查询出全部字段除了group by的字段。

kelvin
关注 私信
文章
92
关注
0
粉丝
0