我們要下載Mysql數據庫(可以去官網中下),然后在下載一個navicat,我們在這里面使用Mysql。等這些准備工作做完之后,我們就正式來寫sql語句了。
首先:我們需要創建一個用戶,然后有一個test的數據庫,這里面是空的,我們可以使用這個: ;
然后是點擊新建查詢按鈕: ;
我們可以在里面寫sql語句了,我們首先要使用sql語句創建幾個表:
CREATE TABLE `customers` ( `customers_id` INT(11) PRIMARY KEY AUTO_INCREMENT, //PRIMARY KEY AUTO_INCREMENT 表示設為主鍵,並自增長 `last_name` VARCHAR(10) NOT NULL, `first_name` VARCHAR(10) NOT NULL, `dob` DATE, `phone` VARCHAR(12) )
(后面幾個表跟上面一樣的,所以我們就不在這里演示了)。
然后就是使用insert ...into...
插入數據:
insert into customers ( last_name,first_name,dob,phone ) values ( '李', '銳','1965-01-01', '800-555-1211'); insert into customers ( last_name,first_name,dob,phone ) values ( '王', '勝', '1968-02-05', '800-555-1212'); insert into customers ( last_name,first_name,dob,phone ) values ( '張', '陽', '1971-03-16', '800-555-1213');
(后面幾個跟上面一樣的,所以我們就不在這里演示了)。
后面幾個表如下:
現在,我們可以寫查詢語句了,
使用比較操作符:
1 語法為:select * from 表名 where _id !=2;
例如:查詢customers表中customer_id不等於2的行:
1 SELECT * FROM customers where customers_id !=2;
使用in操作符:
1 語法為:select * from 表名 where _id in(..,..,);
例如:使用in操作符從customers表中檢索customer_id列的值為2、3、或5的記錄。
1 select * from customers where customers_id in(2,3,5) 2 "not in"恰好相反;
使用邏輯操作符:
1 語法為:select * from 表名 where 字段名>x and 字段名<y
例如:從customers表中檢索dob列大於1970年1月1日並且小於2000年1月1日的客戶:
1 select * from customers where dob>'1970-01-01' and dob<'2000-01-01`
使用ORDER BY子句對行進行排序
order by子句用於對從數據庫檢索出的行進行排序,order by子句可以指定一列或多列(查詢結果會根據這些列進行排序)
,而且必須位於FORM和WHERE子句(如果提供WHERE子句)之后。
desc為倒序排列;
語法為:select * from 表名 ORDER BY 字段名
例如:查詢出products表中的數據,以價格進行排序。
1 select * from products ORDER BY price
使用between操作符:
語法為:select *from 表名 where _id between x and y
當然not between會返回相反的行,between也可以檢索在二個sql語句之間的記錄,當然要求sql語句查詢出的結果要與類型匹配,為整型。
例如:從customers表中檢索customers_id列的值在1和3之間的記錄:
1 select *from customers where customers_id between 1 and 3
現在我們可以用多表查詢,
多表查詢中有一個笛卡兒積,說的是如果在多表查詢中不指定條件,就會導致將一個表中的所有行都連接到另外一個表中的所有行上,這種情況稱為笛卡爾積。出現這種情況結果就會顯示很多行。
里面又分內連接 join...on
和外連接 left jion...on.. ,...right...on
為了方便,通常我們會定義表的一些別名:
例如:同時查看產品名稱和產品類別二個表中的信息。
1 select p.product_id, p.name, 2 2. t.name as type, 3 3. p.description, 4 4. p.price 5 5.from products p join product_types t 6 6. on p.product_type_id = t.product_type_id;