MYSQL SQL語句 之 select

select語句在數據庫操做中是操做頻率最高的語句,使用方式也是多種多樣,它的基本功能是:從表中選取數據,結果存儲在一個結果集中。能夠聯合where,and,or,Order By,distinct,top, like,等一塊兒使用。sql

一. select 最基本的用法以下:

select 字段 from 表名

字段是什麼,選出的結果集中就包括什麼字段數據庫

例如:從users表中只選取字段name的全部數據spa

select name from users

 

字段爲 * 表示選出的結果中包括全部的字段3d

例如:表示從users表中選取全部字段的全部的數據code

 

select * from users

 

二 select跟where,and,or,Order By,distinct,limit, like等命令的組合用法舉例以下

1.選取user表中,年齡大於60歲的 blog

2.選取user表中,年齡大於60歲而且名字中包括字母m的排序

3.選取user表中,年齡大於60歲或者名字中包括字母m的it

4.選取user表中,年齡大於60歲或者名字中包括字母m的,按照年齡逆序排序class

5.select distinct 去重複,只能返回它的目標字段,而沒法返回其餘字段select

6.從表中選取頭N條數據,在MySQL中用 select .... limit  N

7.  表user與表message相關聯,用where in進行連表查詢,in與where搭配使用,用來在 where 子句中規定多個值。

 

。。。。。未完待續。。。。。。

 

 1.選取user表中,年齡大於60歲的 

select * from user where age>60

 

 2.選取user表中,年齡大於60歲而且名字中包括字母m的

select * from user where age>60 and name LIKE '%m%'

   

 3.選取user表中,年齡大於60歲或者名字中包括字母m的

select * from user where age>60 or name LIKE '%m%'

 

   

 4.選取user表中,年齡大於60歲或者名字中包括字母m的,按照年齡逆序排序

  注意:order by 語句默認按照升序對結果集進行排序, desc關鍵字表示逆序

select * from user where age>60 or name LIKE '%m%' order by age desc

  

5.select distinct 去重複,只能返回它的目標字段,而沒法返回其餘字段

注意:

  a. distinct  字段名1,字段名2,...,必須放在要去重字段的開頭

  b. 只在select 語句中使用

  c. distinct 表示對後面的全部參數的拼接取不重複的記錄,即distinct後面全部參數對應的記錄同時同樣時,纔會去重

  d 不能與all同時使用,默認狀況下,查詢時返回的就是全部的結果。

舉例:

選取user表中,年齡大於60歲或者名字中包括字母m的,而且password不重複的數據

select distinct password from user where age>60 or name LIKE '%m%'

 

 

 選取user表中,年齡大於60歲或者名字中包括字母m的,而且password不重複的數據的個數

select count( distinct password) from user where age>60 or name LIKE '%m%'

 6.從表中選取頭N條數據,在MySQL中用 select .... limit  N

 舉例:選取user表中,年齡大於60歲或者名字中包括字母m的 的頭2條數據

select * from user where age>60 or name LIKE '%m%' LIMIT 2

 

 

 7.  表user與表message相關聯,用where in進行連表查詢,in與where搭配使用,用來在 where 子句中規定多個值。

 

 舉例:

在message中找出年齡大於60的message

select * from message  where userid in (select id  from user where age >60)

相關文章
相關標籤/搜索