1. 程式人生 > >mysql 常用語句

mysql 常用語句

一:對某一個欄位分組後查詢重複記錄:
(關鍵詞:having)
select station_id,count(*) as count from historyenergy_logs where DATE_FORMAT(historytime,’%Y-%m-%d’)=DATE_FORMAT(‘2017-11-22’,’%Y-%m-%d’) and type=0 group by station_id having count>1;

二:查詢某幾個月的總髮電量,如果沒有,則定義發電量為0,同時去掉重複的部分,拿到重複資料中最大電量的(eg:得到5-9月的總髮電量,同時去掉重複月份的發電量)
(關鍵詞:ifnull,max(xx) group by)
select IFNULL(sum(historyenergy_logs_group_by_month.max_energy),0) as five_to_nine_month_energy from (select month,max(energy) as max_energy from historyenergy_logs where station_id=xxx and month in(5,6,7,8,9) and type=1 group by month order by energy) historyenergy_logs_group_by_month

三:去重標誌:
(關鍵詞:distinct )
select sum( distinct energy) from historyenergy_logs where station_id=xxx and (month=5 or month=6 or month=7 or month=8 or month=11) and type=1 group by month order by energy desc

order by 根據指定欄位,指定欄位中某些內容進行排序:
eg:根據id的後四位進行排序。 id:SH-SD-2018-0012
select * from projects where province=? order by (right(id,4)) desc ;