查询语句
语法格式:
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 = ‘李四’;