mysql 常用查詢模型

2021-10-06 22:19:32 字數 2216 閱讀 1302

1.乙個欄位有多個可取值,先要統計每個可取值數量

demo1 統計從 常駐/流動人口

-- 統計常駐人口、流動人口

-- migration_type 人口流動 (1:常住;2:常訪客;3:臨時訪客)

select sum(mobile) as mobile,sum(permanent) as permanent

from

(select

case when migration_type='1' then 1 else 0 end mobile ,

case when migration_type in('2','3') then 1 else 0 end permanent

from sys_staff_info where domain = 'default') tmp

demo2

-- 分別統計統計獨居老人、養犬人員、五保戶、重點關注人群、其他

-- people_type 人群型別(0:正常;1:獨居老人;2:養犬人員;3:五保戶;4:疆藏;5:精神病;6:刑滿釋放;7:社群矯正;8:吸毒人員;9:上訪人員)

select sum(olderly_alone) as olderly_alone,sum(dog_keeeper) as dog_keeeper,

sum(low_salary) as low_salary,sum(focus_crowd) as focus_crowd,sum(others) as others

from

(select

case when people_type='1' then 1 else 0 end olderly_alone,

case when people_type='2' then 1 else 0 end dog_keeeper,

case when people_type='3' then 1 else 0 end low_salary,

case when people_type in('4','5','6','7','8','9') then 1 else 0 end focus_crowd,

case when people_type in('0','') then 1 else 0 end others

from sys_staff_info where domain = 'default') tmp

demo3

-- 統計疫情級別

-- country 國籍(0:中國;1:外國) sys_city 0:低;1:中;2:高

select sum(low) as low, sum(middle) as middle, sum(high) as high, sum(alien) as alien from (

select case when (tb.level is null or tb.level = '0') and ta.country = '0' then 1 else 0 end low,

case when tb.level = '1' and ta.country = '0' then 1 else 0 end middle,

case when tb.level = '2' and ta.country = '0' then 1 else 0 end high,

case when ta.country = '1' then 1 else 0 end alien

from sys_staff_info ta left join sys_city tb on ta.city = tb.name

where domain = 'default'

) ta

2. 一些設計表時注意

-- uft下中文 能存33個中文字元。如果有空值,最好 not null default ''

desc_info varchar(100) not null default '' comment '資料集備註資訊'

-- 日期自動更新

updated_time datetime not null default current_timestamp on update current_timestamp comment '更新日期'

-- 多種型別,可以用char(1) 。mysql不支援bool,用char(1) or tinyint

mysql 查詢 常用 mysql常用查詢

一.group concat函式,以指定的分割符合並列,與group by 一起用 例 selectgroup concat c.columnname separator group by 二.preparedstatement.return generated keys 得到剛剛插入記錄的id p...

mysql常用的查詢 MySQL常用查詢

資料庫 1.查詢所有資料的大小 data length 資料大小 index length 索引大小 select concat round sum data length index length 1024 1024,2 mb as data from information schema.tab...

mysql常用的查詢 MySQL常用查詢

select from unixtime create time,y m as time,sum sales amount sales amount sum from sales group by time 執行結果如下 查詢每年的銷售額 select from unixtime create ti...