在mysql資料查詢中,最基本的查詢語句是:
select*from table_name where condition;
假設資料庫中表students中有id, name, age, birthday四個字段
*代表表中所有字段,在查詢時可結合實際選取自己需要查詢的字段,即:
select name, id, age from students;
在查詢時,輸入的字段順序即為查詢結果顯示的順序。
如果某個欄位下的資料有重複,但我們只想看到不重複的,可使用關鍵字distinct:
selectdistinct name age from students;
似乎distinct後只能跟著乙個欄位名 ,用distinct同時查詢多個字段暫時還沒看到;
在mysql中也可以使用簡單的四則運算,如:
select name, age-18from students;
可以給進行四則運算後的欄位名新增別名:
select name, age-18as child from students;
其實在上述語句中as也可以不寫,寫上似乎只是穩了增加理解和可讀性;
與python類似,mysql也也可以設定顯示格式,和字串拼接差不多:
select concat(name, '同學的年齡是:
', age-
18) falseage from students;
concat()提供拼接字串和數值的功能。
在mysql中支援帶關係運算子和邏輯運算子的條件資料查詢,如<,>, and, or, not等, 都是在最後的where子句中實現的;
select name, age from students where id>10 ;
select name from students where age between10and
20;
上面**查詢了年齡在10到20歲學生的姓名。
查詢年齡不在此範圍的學生,可以使用not:
select name from age notbetween
10and
20;
可使用關鍵字not null, 實現判斷欄位的數值是否為空的條件查詢。
select name from students where age isnull;
相反,可使用not找到與此相反的結果:
select name from students where age isnotnull;
或者:
select name from students wherenot age is
null;
in關鍵字提供了集合查詢:
select name from students where age in (18,19,27,25)
如果需要查詢不在該集合中的資料,可在in前加上not;
使用like的模糊查詢:
"_"萬用字元,該萬用字元能匹配單個字元;
"%"萬用字元可以匹配任意長度的字串。
select name from students where name like'a%';
查詢名字以a開頭的學生姓名;
like模糊查詢可以和not關鍵字配合使用,達到相反的效果。
select field1, field2, field3 from table_name where condition orderby filed desc;
order by field desc為按照field降序排序,如果寫為order by field;則為公升序排序,即預設為公升序(asc)。
也可按照乙個字段公升序,乙個字段降序同時排序:
select*from table_name where condition order
by field1 by
asc, field2 desc;
通過limit關鍵字限制查詢結果的顯示數量:
select name from students where age>18 limit offset_start, row_count;
如:
select*from students where age is
null
order
by name limit 5, 5;
MYSQL實驗三 資料查詢 單錶查詢
一.實驗目的 1.掌握select語句的基本語法格式 2.掌握select語句的執行方法 3.掌握select語句的group by和order by字句的作用 題目要求 在公司的部門員工管理資料庫的bumen表和yuangong表上進行資訊查詢。bumen表和yuangong表的定義如下所示。然後...
MySQL資料查詢
1.基本查詢語句 select語句是最常用的查詢語句,它的使用方式有些複雜,但功能卻相當強大。select selection list 要查詢的內容,選擇哪些列 from資料表名 制定資料表 where primary constraint 查詢時需要滿足的條件,行必須滿足條件 2.單錶查詢 單錶...
mysql資料連線查詢 mysql 資料查詢
連線查詢 1.連線 join 也稱 連線,從兩個關係的笛卡爾積中選擇屬性間滿足一定條件的元組。等值連線 為 的連線運算稱為等值連線。從關係r和s的廣義笛卡爾積中選取a b屬性值相等的元組。自然連線 一種特殊的等值連線。要求關係中進行比較的分量必須是同名的屬性組,並且在結果中把重複的屬性去掉。外連線 ...