简单查询
select columna columnb from mytable;
order by查询
select college, region, seed from tournament order by region, seed;select college, region as r, seed as s from tournament order by r, s;select college, region, seed from tournament order by 2, 3;
--要以相反的顺序进行分类,应把desc(降序)关键字添加到order by子句中的列名称中。默认值为升序;该值可以使用asc关键词明确地指定。
select a, count(b) from test_table order by a desc;
group by having查询
select a, count(b) from test_table group by a desc;select count(col1) as col2 from t group by col2 having col2 = 2;
having不能用于应被用于where子句的条目,不能编写如下语句:
select col_name from tbl_name having col_name > 0;
而应该这么编写
select col_name from tbl_name where col_name > 0;
having子句可以引用总计函数,而where子句不能引用:
select user, max(salary) from users group by user having max(salary)>10;
limit查询
select * from tbl limit 10; # retrieve rows 0-9;select * from tbl limit 5,10; # retrieve rows 6-15;
如果要恢复从某个偏移量到结果集合的末端之间的所有的行,您可以对第二个参数是使用比较大的数。--以下语句可以恢复从第96行到最后的所有行:
select * from tbl limit 95,18446744073709551615;
select...into outfile
select...into outfile 'file_name'形式的select可以把被选择的行写入一个文件中。该文件被创建到服务器主机上,因此您必须拥有file权限,才能使用此语法。file_name不能是一个原有的文件。
select...into outfile语句的主要作用是让您可以非常快速地把一个表转储到服务器机器上。如果您想要在服务器主机之外的部分客户主机上创建结果文件,您不能使用select...into outfile。在这种情况下,您应该在客户主机上使用比如“mysql –e select ... > file_name”的命令,来生成文件。
select...into outfile是load data infile的补语;用于语句的exort_options部分的语法包括部分fields和lines子句,这些子句与load data infile语句同时使用。
在下面的例子中,生成一个文件,各值用逗号隔开。这种格式可以被许多程序使用
select a,b,a+b into outfile '/tmp/result.text' fields terminated by ',' optionally enclosed by '' lines terminated by '\n'from test_table;
如果您使用into dumpfile代替into outfile,则mysql只把一行写入到文件中,不对任何列或行进行终止,也不执行任何转义处理。如果您想要把一个blob值存储到文件中,则这个语句是有用的。
union
union用于把来自许多select语句的结果组合到一个结果集合中,语法如下:
select ...union [all | distinct]select ...[union [all | distinct]select ...]
列于每个select语句的对应位置的被选择的列应具有相同的类型。(例如,被第一个语句选择的第一列应和被其它语句选择的第一列具有相同的类型。)在第一个select语句中被使用的列名称也被用于结果的列名称。
如果您对union不使用关键词all,则所有返回的行都是唯一的,如同您已经对整个结果集合使用了distinct。如果您指定了all,您会从所有用过的select语句中得到所有匹配的行。
您可以在同一查询中混合union all和union distinct。被混合的union类型按照这样的方式对待,即distict共用体覆盖位于其左边的所有all共用体。distinct共用体可以使用union distinct明确地生成,或使用union(后面不加distinct或all关键词)隐含地生成。
简单例子
(select a from tbl_name where a=10 and b=1)union(select a from tbl_name where a=11 and b=2)order by a limit 10;
all, distinct和distinctrow
all, distinct和distinctrow选项指定是否重复行应被返回。如果这些选项没有被给定,则默认值为all(所有的匹配行被返回)。distinct和distinctrow是同义词,用于指定结果集合中的重复行应被删除。
select distinct a from table_name;select count(distinct a) from table_name;