Mysql知識點-日常更新
一、left join 中on和where條件過濾介紹
簡介:數據庫在通過連接兩張或多張表來返回記錄時,都會生成一張中間的臨時表,然後再將這張臨時表返回給用戶。 在使用left jion時,on和where條件的區別如下:
1、on條件是在生成臨時表時使用的條件,它不管on中的條件是否爲真,都會返回左邊表中的記錄。
2、where條件是在臨時表生成好後,再對臨時表進行過濾的條件。這時已經沒有left join的含義(必須返回左邊表的記錄)了,條件不爲真的就全部過濾掉。
二、limit1,1 和limit 1 offset 1區別
limit begin,number:從(包含)begin數據開始查詢number條數據。
limit number offset begin:從begin後一條數據開始查詢number條數據。
三、IFNULL(column,null)
如果查詢的字段爲空可以設置成null當然你也可以設置成0或者其他的信息。
四、根據數值字段進行排序,可並列但是要連續
sql語句:
select s.Score,
(select count(distinct Score) from Scores where Score>=s.Score) as Rank from Scores s
order by s.Score desc
解釋:通過cout(distinct score)來計算比Score大於等於的個數對應的也就是名次,因爲order by Score排序了。
五、mybatis
@Deprecated
@Select("select id,mockexam_section as section,id as sectionId"
+ " from t_p_qb_mockexam_section"
+ " where mockexam_charpter_id = #{charpterId} and is_delete = 0"
+ " order by mockexam_section_idx asc")
@Results({
@Result(property = "questionList",column = "sectionId",
many = @Many(select = "com.zikaoshu.baseinfo.mapper.BaseinfoQuestionMapper.listQuestionResDto"))
})
List<SectionQuestionDto> listSectionQuestionDto(@Param("charpterId") Integer charpterId);
/**
* 根據模考章節部分id查詢該章節下面所有試題
*/
@Deprecated
@Select("select id,type,discuss_title as discussTitle,stem1,material,a,b,c,d,e,answer,analysis,mockeaxm_section_id as sectionId"
+ " from t_p_qb_question_mockexam"
+ " where mockeaxm_section_id = #{id} and is_delete = 0"
+ " order by q_sequence,gmt_create asc")
List<QuestionResDto> listQuestionResDto(@Param("id") Integer id);
6、根據A表字段判斷是查詢B表還是C表
SELECT a.id, a.type, b.question , c.content
FROM table_a as a
LEFT JOIN table_b as b on a.id= b.aId and a.type = 2
LEFT JOIN table_c as c on a.id= c.aId and a.type = 3
七、MySQL表根據一個或多個字段去重
// 根據以下SQL查詢出來重複的數據,然後手動全選手動刪除
select * from tableA a
where (a.col1,a.col2,a.col3,a.col4) in (select col1,col2,col3,col4 from tableA group by col1,col2,col3,col4 having count(*) > 1)
and id not in (select min(id) from tableA group by col1,col2,col3,col4 having count(*)>1)