一、Mysql中查询5条不重复的数据
方法一:
SELECT * FROM `life_member`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`)))
ORDER BY id LIMIT 1;
方法二:
SELECT *
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`))+(SELECT MIN(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 1;
二、读取mysql数据库中内容,并换行写入到文件中
# coding=gbk
from pymysql import *
def deal():
#连接数据库
conn = connect(host='***', port=3306, database='***', user='***',
password='***', charset='utf8')
#创建游标
cs1 = conn.cursor()
cs1.execute("SELECT 字段名 from 表名")
#将查询到的数据存入到列表中
pnlist = []
#读取所有数据
alldata = cs1.fetchall()
#遍历所有数据
for singl_company in alldata:
#将第一个数据追加到列表中
pnlist.append(singl_company[0])
#关闭游标
cs1.close()
#数据库关闭
conn.close()
#将数据存入到目标文件中
try:
fp = open('需要写入的文件路径', "w+")
for item in pnlist:
fp.write(str(item) + "\n") # 一条记录占一行
fp.close()
except IOError:
print("fail to open file")
if __name__ == '__main__':
deal()