9、mysql数据表中数据的查询(1)
生活随笔
收集整理的這篇文章主要介紹了
9、mysql数据表中数据的查询(1)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用數據庫最終要的莫過于查詢數據,所以這里將會詳細的介紹mysql數據庫中查詢語句的使用
普通查詢
使用基本的select關鍵字進行查詢,其語法及使用如下
# 格式 select [select選項] 字段 [as 別名] from 數據表;# 查詢出所有字段的值,不建議直接寫* select * from user;# 查詢出指定字段的值 select id,name from user;# 過濾掉指定字段重復的數據,自動過濾調用多余的id和name兩個字段值相同的記錄 select distinct id,name from user;# 給查詢出的字段去別名 select name as user_name from user;帶有子句的查詢
mysql中的子句有5類,如下:
| where | 用于條件判斷,過濾數據,判斷條件有:> ,< , >= ,<= ,!= ,like ,between and ,in/not in ,and ,or 。 where是唯一一個直接從磁盤獲取數據時就進行判斷的條件 | where id = 5 |
| group by | 用于引導分組查詢語句 | group by age |
| having | 作用類似于where,但是它是對內存中的數據進行過濾,通常和group by連用,可以使用字段的別名進行條件判斷 | group by age having count(age) > 5 |
| order by | 排序查詢,對查詢出的數據進行排序,asc表示升序,desc表示降序 | order by id desc |
| limit | 用于限制返回查詢的數據記錄數,一般用于分頁使用 | limit 10 |
以上幾個子句可以混合使用,接下來寫幾個實例,來看一下如何使用
# 使用where進行條件判斷 select name,age from user where id > 2;# 獲取當前表中前10條數據 select name,age from user limit 10;# 獲取表中第5到第8條數據 select name , age from user limit 4,4; # 獲取表中第i到第j條數據 select name ,age from user limit (i-1) , (j-i-1) ;# 查詢user表中有哪幾類名字 select name from user group by name;# 將所有數據按著年齡大小排序(NULL值默認是最小的) select name,age from user order by age desc;# 查詢相同名字數量大于2的有幾人,名字是什么(count是一個內置的函數,用于計算個數,有幾條記錄,count函數的值就為幾) select name ,count(name) from user group by name having count(name) > 2;聯合查詢
聯合查詢指的是將多個查詢結果組成一個查詢結果返回,使用union關鍵字完成聯合查詢,注意每一個查詢結果的返回字段數、類型必須一致,一般在處理多個類型不同但是數據結構相同的表時使用,實例如下:
# 聯合查詢,過濾掉所有對應字段值都相同的數據 select name,age from user1 where id < 5 union select name,age from user2 where id > 7;# 聯合查詢,不會過濾掉所有對應字段值都相同的數據 select name,age from user1 where id < 5 union all select name,age from user2 where id > 7;正則查詢
# ^匹配以特定字符串開頭的記錄 select id,name,age from user where name regexp '^li';# $匹配以特定字符串結尾的記錄 select id,name,age from user where name regexp 'si$';# .匹配字符串的任意一個字符(只要帶s的都會被查詢到) select id,name,age from user where name regexp '.s';# [字符集合] 匹配字符集合中的任意一個字符,只要name值帶有i或者s的都會被查詢到 select id,name,age from user where name regexp '[is]';# [^字符集合] 匹配除字符集合以外的任意一個字符 select id,name,age from user where name regexp '[^is]';# S1|S2|S3 匹配S1,S2,S3中的任意一個字符串 select id,name,age from user where name regexp 'si|san';# a*b 匹配b之前出現過a的記錄,包括0次 select id,name,age from user where name regexp 'l*s';# a+b 匹配b之前出現過a的記錄,至少1次 select id,name,age from user where name regexp 'l+s';# a{N} 匹配字符串a連續出現過N次的記錄 select id,name,age from user where name regexp 'i{2}';# a{M,N} 匹配字符串至少出現過M次,至多出現過N次的記錄 select id,name,age from user where name regexp 'i{2,5}';?
總結
以上是生活随笔為你收集整理的9、mysql数据表中数据的查询(1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2008电脑配置单(2008电脑配置)
- 下一篇: 12、数据库的设计范式