軟體測試中常用的SQL語句
查詢語句
語法格式:
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUN
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFF
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
常用舉例
--查詢member表中所有的會員記錄
SELECT * FROM member;
其中“*”號表示顯示符合條件的記錄的所有欄位
在資料庫中儲存型別為文字的欄位查詢
--查詢member表中姓名叫張三的會員
SELECT * FROM member WHERE name = '張三';
--查詢member表中所有姓張的會員
SELECT * FROM member WHERE name like ‘張%’;
其中“%”表示任意字元都符合條件。即只有滿足姓名中第1個字元是“張”就滿足查詢條件
--查詢member表中所有名字包含“三”的會員
SELECT * FROM member WHERE name like ‘%
由於“三”字前後都含有百分號“%”,這就表示“三”字前面和“三”字後面不管是任何字元都滿足查詢條件,即使“三”字前後沒有字元也符合條件
在資料庫中年齡儲存為數字型別的欄位查詢
--查詢member表中年齡等於18的會員
SELECT * FROM member WHERE age = 18;
--查詢member表中年齡大於等於18的會員
SELECT * FROM member WHERE age >= 18;
--查詢member表中年齡在18和30之間的會員包含18歲和30歲
SELECT * FROM member WHERE age >=18 AND age <=30;
--查詢member表中年齡在18和30之間的會員不包含18歲和30歲
SELECT * FROM member WHERE age >18 AND age <30;
在資料庫中儲存為日期型別欄位查詢
--查詢member表中在2009-11-30註冊的會員
SELECT * FROM member WHERE reg_date = “2009-11-30”;
其中reg_date是表中註冊日期欄位。由於不同資料庫中查詢語句有時稍有區別。以上使用語句在MYSQL資料庫中可以執行。但要想在Oracle資料庫中使用就得稍加修改,如下:
SELECT * FROM member WHERE reg_date = to_date(“2009-11-30”,”YYYY-MM-DD”);
下面的SQL語句適用IBM的DB2資料庫:
SELECT * FROM member WHERE reg_date = date(“2009-11-30”);
“YYYY-MM-DD”表示日期格式為(年-月-日)
--查詢member表中2009-11-01到2009-11-30之間註冊的會員
SELECT * FROM member WHERE reg_date BETWEEN “2009-11-01” AND “2009-11-30”;
適用於Oracle資料庫的查詢語句:
SELECT * FROM member WHERE reg_date BETWEEN to_date(“2009-11-01”,”YYYY-MM-DD”) AND to_date(“2009-11-30”, ”YYYY-MM-DD”);
適用於IBM DB2資料庫的語句:
SELECT * FROM member WHERE reg_date BETWEEN date(“2009-11-01”) AND date(“2009-11-30”);
新增記錄語句
語法格式:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
常用舉例
INSERT member(name,age,reg_date) values(‘張三’,20,’2009-11-30’);
更新記錄語句
語法格式:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
常用舉例
--更新姓名為張三的會員年齡為19歲
UPDATE member SET age = 19 WHERE name = ‘張三’;
刪除記錄語句
語法格式:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
常用舉例
--刪除姓名為李四的會員記錄
DELETE FROM member WHERE name = ‘李四’;