1. 程式人生 > >《MYSQL必知必會》學習筆記(4-8章)

《MYSQL必知必會》學習筆記(4-8章)

以下為《mysql必然知必會》第4-8章學習筆記,主要涉及查詢的select語句,where語句和like萬用字元。

SELECT語句

1.檢索一列

Select name from products;

2.檢索多列

Select id,name,price fromproducts;

3.檢索所有列

Select * from products;

4.檢索id列(返回唯一值)

Select distinct id from products;

5.檢索name列(返回前5行)

Select name from products limit 5;

6.檢索name列(返回6-10行);

Select name from products limit 5,5;

7.檢索name列,並以name列排序

Select name from products order by name;

8.檢索id ,price,name三列,並以price,name排序,首先按price,再按name。

Select id,price,name from productsorder by price,name;

9.檢索id,price,name三列,並以price降序排列(升序是預設的,ASC)

Select id,price,name fromproducts order by price desc;

10.檢索price列中的最大值

Select price from products order by pricedesc limit 1;

WHERE語句

1.   檢索name,price兩列,只返回price為2.5的行

Select name,price from products where price=2.5;

2.檢索name,price兩列,只返回name為fuse的行

Select name,price from products where name=‘fuse’;

3.檢索name,price兩列,只返回price小於10的行

Select name,price from products where price<10;

4.檢索出不是由id為1003供應商製造的產品

Select id pro_name from products where id<>1003;(或者用!=)

5.檢索價格在5元-10元之間的產品

Select name price from products where pricebetween 5 and 10;

6.檢索價格為空的產品列表

Select name from products where price isnull;

組合WHERE子句

1.   檢索1003供應商製作且價格小於等於10元的所有產品名稱和價格

Select name and price from products whereprice <=10 and id=1003;

2.   檢索1002 或者1003供應商製作的產品名稱和價格

Select name,price from products where id=1002 or id=1003;

Select name,price from products where id in(1002,1003);

3.   檢索除1002,1003供應商之外生產的所有產品名稱和價格;

Select name,price from products where id not in(1002,1003);

LIKE操作符

1.檢索以產品名稱以jet開頭的所有產品的id和name

Select id,name from products where name like‘jet%’;

2.檢索產品名稱以s開頭,e結尾的所有產品

Select name from products where name like‘s%e’;

3.檢索產品名稱第二位到最後一位是ton anvil的產品

Select name from products where name like‘_ton anvil’;

注意%_的區別:%可以匹配0,1,多個字元,而_僅可以匹配1個字元。