關於MySQL5.7 這幾天的總結(json類型)
一開始,老板讓調整一下 innodb_buffer_pool_size 大小,因為這臺機器內存大。
看了下內存,16G,再SQL下面命令,得到結果是4G。
SELECT @@innodb_buffer_pool_size;
果斷vim /etc/my.cnf
修改了 innodb_buffer_pool_size = 8G # (adjust value here, 50%-70% of total RAM)
括號中內容是官方給的建議。
然後再執行下面的命令,調整到8G,這樣不用重啟mysql服務,即調整完畢。
SET GLOBAL innodb_buffer_pool_size=8589934592; -- 8G
其它的幾個查詢:
-- show status like ‘Threads%‘; -- 連接數 -- show processlist; -- 查看連接,可以知道當前有哪些IP連接 -- select * from information_schema.processlist order by id; -- 查看連接
最近才知道, mysql從5.7版本開始,增加了新的字段類型: json
所以在centos6.5上裝了個5.7版本作為平時測試用.
#----------------------------------------------------------------------# # 修改yum源為aliyun # 先備份: mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup # 下載配置文件 註意 centos版本 wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo yum makecache # 生成緩存 # yum -y update # 升級所有包同時也升級軟件和系統內核 不是必要 #----------------------------------------------------------------------# ### --------------------------------------------------------------------### # 安裝 mysql 5.7版本 不同於低版本的安裝,稍微復雜。 yum list installed | grep mysql # 檢測系統是否自帶安裝mysql yum -y remove mysql-libs.x86_64 # 刪除系統自帶的mysql及其依賴 # 給CentOS添加rpm源,並且選擇較新的源 wget dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm --no-check-certificate yum install mysql-community-release-el6-5.noarch.rpm vim /etc/yum.repos.d/mysql-community.repo # 編輯此文件,將MySQL 5.7下的 enabled=1 低版本的改成 enabled=0 yum repolist enabled | grep mysql # 檢查mysql57的源是否開啟 # 安裝mysql 服務器 yum install mysql-community-server cat /var/log/mysqld.log | grep "password" # 找到臨時密碼 # 如果沒有找到密碼,則可能使用之前本機舊版本的密碼。 service mysqld start chkconfig mysqld on mysql_secure_installation # 設置安全選項 mysql -uroot -p # 輸入臨時密碼 SET PASSWORD = PASSWORD(‘your password‘); # 設置新密碼 # 如果遠程連接出錯:‘performance_schema.session_variables‘ doesn‘t exist # 則操作以下命令並重啟服務後,再連接 mysql_upgrade -u root -p --force service mysqld restart
設計表的時候, 字段類型直接選json 就像平常選varchar一樣.
插入數據的時候, 需要轉成JSON_OBJECT 。 而JSON_ARRAY 用來將多個值存成數組。 如下面的示例:
SELECT mac, JSON_OBJECT(‘e1‘,JSON_ARRAY (round( AVG( value ->> ‘$.e1‘ ), 3 ),MIN( value ->> ‘$.e1‘ ),MAX( value ->> ‘$.e1‘ )),
‘e2‘,JSON_ARRAY (round( AVG( value ->> ‘$.e2‘ ), 3 ),MIN( value ->> ‘$.e2‘ ),MAX( value ->> ‘$.e2‘))) as json
FROM history WHERE mac =‘522099e6660004‘ and time between ‘2018-08-07 00:00:00‘ AND ‘2018-08-08 00:00:00‘ GROUP BY mac
value是表中的字段名,e1、e2是此字段中json的key, AVG/MIN/MAX不用多說了,大家都知道。 此句的作用是以某mac字段和時間為限定,分別取出e1的avg/min/max,然後賦給一個新的數組 “e1", 取出e2的avg/min/max,然後賦給一個新的數組 “e2",然後組成json對象,得到下面的結果。
{"e1": [25.568, 12, 121], "e2": [28.631, 12, 182]}
取值的時候,取json裏面的鍵,可以直接用SQL語句,像下面這麽寫:
value -> ‘$.e1‘ 表示取出json型字段名為value中的 e1 健的值. 即使取出的數字,也帶有雙引號
value ->> ‘$.e1‘ 則取出數字不帶有雙引號, 但此時仍然不是數值類型. JSON_UNQUOTE(json_extract(json,‘$.attr‘)) 也可以去掉引號.
value ->> ‘$.e1‘+0 則會強制將取出的字符型數字轉為數值類型. CAST(‘123‘ AS SIGNED) 或 CONVERT(‘123‘,SIGNED)的函數也行,但是執行速度沒有直接 +0 快. (必須看起來的確是數字)
如果跑py腳本,沒有安裝環境,則依次執行以下命令。
或者參考更詳細的python升級2.7 https://www.cnblogs.com/frx9527/p/python27.html
yum install gcc gcc-c++ -y yum -y install mysql-devel yum install python-devel pip install --upgrade pip pip install MySQL-python -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
以下腳本運行在python2.7 因為python3以上不再有 MySQLdb
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb, time, datetime, json print(datetime.datetime.now()) HOST = ‘node-6‘ db = MySQLdb.connect(HOST, "root", "123456", "monitor_db") cursor = db.cursor() def get_date(str_date): t = time.strptime(str_date, ‘%Y-%m-%d‘) y, m, d = t[0:3] return datetime.datetime(y, m, d) def insert_device_data(cursor, data): sql = "INSERT INTO history_daily (mac, time, json) VALUES (%s, %s, %s)" # print sql cursor.executemany(sql, data) def fetch_device_minutely_data(cursor, start, end, mac): try: sql = ‘‘‘ SELECT mac, CASE version %s END json FROM history WHERE mac =‘%s‘ and time between ‘%s‘ AND ‘%s‘ GROUP BY mac, version ‘‘‘ % (jsonkey, mac, start, end) # print(sql) # 壯觀的 case ... when cursor.execute(sql) data = cursor.fetchall() if data: for d in data: mac = d[0] json = d[1] device_data = [] device_data.append((mac, start, json)) insert_device_data(cursor, tuple(device_data)) except MySQLdb.OperationalError, e: print(e) time.sleep(10) db = MySQLdb.connect(HOST, "root", "123456", "monitor_db") cursor = db.cursor() fetch_device_minutely_data(cursor, start, end, mac) # 設備表 id , version version_sql = ‘SELECT id, version FROM device_version GROUP BY id, version‘ cursor.execute(version_sql) versions = cursor.fetchall() # version 從2到10 jsonkey = "" if versions: for version in versions: print (version[0]) sensor_sql = ‘‘‘ SELECT s.sensor_key FROM device_version_sensor dvs,sensor s WHERE dvs.sensor_id = s.id AND dvs.device_version_id = ‘%d‘ ‘‘‘ % (version[0]) # e1 e2 e3 ... cursor.execute(sensor_sql) keys = cursor.fetchall() if keys: jsonkey += "WHEN " + str(int(version[1])) + " THEN JSON_OBJECT(" for i, sensorKey in enumerate(keys): key = sensorKey[0] jsonkey += "‘" + str(key) + "‘,JSON_ARRAY (round( AVG( value ->> ‘$." + str( key) + "‘+0 ), 3 ),MIN( value ->> ‘$." + str( key) + "‘+0 ), MAX( value ->> ‘$." + str(key) + "‘+0 ))" if i != len(keys) - 1: jsonkey += "," jsonkey += ")" # mac 列表 sql_mac = ‘SELECT DISTINCT mac FROM `history` where mac is not NULL‘; cursor.execute(sql_mac) mac_tuple = cursor.fetchall() # version 從2到10 start_date = get_date((datetime.datetime.now() + datetime.timedelta(days=-6)).strftime("%Y-%m-%d")) end_date = get_date((datetime.datetime.now()).strftime("%Y-%m-%d")) days = (end_date - start_date).days for i in range(days): start_day = start_date + datetime.timedelta(days=i) end_day = start_date + datetime.timedelta(days=i + 1) for mac in mac_tuple: # print (mac[0]) fetch_device_minutely_data(cursor, start_day, end_day, mac[0]) db.commit() db.close() print(datetime.datetime.now())
SQL語句創建簡單的定時任務,每天淩晨執行前一天的數據匯總,求取表中每個城市的最大值。
對應地將json中的quality值由漢字轉換為數字,先存入臨時表,最後求取個最大值存放到 quality_daily 表中。如果SQL搞定沒問題,就沒必要麻煩python了。
定義:
begin -- 取出所有 quality INSERT INTO quality_tmp ( time, quality, city_code ) SELECT DATE_FORMAT( time, "%Y-%m-%d" ) AS time, IF ( aqi_json ->> "$.quality" = "優", 1, IF ( aqi_json ->> "$.quality" = "良", 2, IF ( aqi_json ->> "$.quality" = "輕度汙染", 3, IF ( aqi_json ->> "$.quality" = "中度汙染", 4, IF ( aqi_json ->> "$.quality" = "重度汙染", 5, IF(aqi_json ->> "$.quality" = "嚴重汙染", 6, 0)) ) ) ) ) AS quality, city_code FROM `hangzhou_aqi` WHERE time >= date_sub( curdate( ), INTERVAL 1 DAY ) AND time < curdate( ); -- 求出最大值 INSERT into quality_daily(time,quality,city_code) SELECT time, max(quality), city_code from quality_tmp GROUP BY time,city_code ; -- 清空臨時表 delete from quality_tmp; end
設定 計劃 為每一天。
關於MySQL5.7 這幾天的總結(json類型)