sql 常用查詢和優化筆記

2021-10-06 11:18:26 字數 1307 閱讀 3299

1.sum(if)

select  sum(if(status=1,1,0))as s1, sum(if(status=2,1,0))as s2   from vehicle;

2.count(if)

select  count(status=1 or null) as s1,count(status=2 or null) as s2 from vehicle;

注:不要少了後面的or null,因為count只有在遇見null時不計數,前者單引號內不管輸入什麼值都會統計出所有記錄數。加上or null ,第乙個表示式是true就是不執行or後面的表示式,第乙個表示式是false 執行or後面的表示式 。

select

case when 條件1

then 結果1

when 條件2

then 結果2

else 結果3

end as isonline

from

vehicle

select * from student where stuid in (select stuid from score where ...);

in先執行裡面的子查詢,後執行外面的主查詢,因此適用於主查詢記錄較大且有索引時

select * from student where exists (select stuid from score where ...);

exists先執行外面的主查詢,後執行裡面的子查詢,因此適用於子查詢記錄較大時

#:將傳入的資料都當成乙個字串,會對自動傳入的資料加乙個雙引號;可以防止防止sql注入。

$:將傳入的資料直接顯示生成在sql中,方式一般用於傳入資料庫物件,例如傳入表名,欄位名。

select * from tablename limit 10 offset 100;(全表掃瞄) ----->  select * from tablename where id >100 offset 10(根據指標定位)

mysql中用:replace into 

mybaits:

insert into  t_user(openid, name, gender, phonenumber)

values (#,#,#,#)

on duplicate key update

name = #,

gender = #,

phonenumber = #

筆記 索引和SQL查詢優化(待補充)

參考書 高效能 mysql 書中索引和sql的優化經驗不但適用於mysql,大部分也適用於postgresql oracle db2 sqlserver,以及mongodb。一.索引型別 1.b樹索引 2.雜湊索引 3.空間索引 地理空間資料 4.全文索引 二.索引使用策略 1.欄位中不應該有表示式...

SQL查詢和優化(三)

給查詢結果排序 select empno,ename,hredate from emp where deptno 10 order by hiredate asc 也可以這樣寫 select empno,ename,hredate from emp where deptno 10 orderby3 ...

SQL查詢和優化(五)

一 插入新記錄 建立測試表,各列都有預設值。create table test c1 varchar2 10 defaut 預設1 c2 varchar2 10 defaut 預設2 c3 varchar2 10 defaut 預設3 c4 date default sysdate 新增資料如下 i...