连接MySQL数据库
- mysql -hlocalhost -uroot -p(为了连接到MySQL,需要以下信息:主机名(计算机名)————如果连接到本地MySQL服务器,为localhost;端口(如果使用默认端口3306之外的端口);一个合法的用户名;用户口令(如果需要)。)
检索MySQL中的数据库
- use databases;
检索数据库里的表
- show tables;
检索表里的列
- show columns from 表;
- describe 表(MySQL支持用DESCRIBE作为SHOW COLUMNS FROM的一种快捷方式)
检索表中的指定列
- select 列 from 表;(指定列可以是多个,用“,”分隔。如果是所以列的话,用通配符“*”)
检索表中指定列的不同行
- select distinct 列 from 表;(distinct可以将列中的行去重)
限制检索表中指定列的行数
- select 列 from 表 limit 数字;(从第一行开始检索“数字”代表的行数)
- select 列 from 表 limit 数字,数字;(以第一个“数字”为第一行检索第二个“数字”代表的行数,如果数量不够,则能返回剩下所以的行)
使用完全限定的表名来检索列
- select 表a.列 from 表a;
- select 表a.列 from 数据库a.表a;(两者功能相同)
order by子句排序检索
- select 列 from 表 order by 列;(以列的字母顺序排列)
- select 列1,列2,列3 from 表 order by 列2,列3;(仅在多个行具有相同的“列2”值时才对产品按“列3”进行排序,如果“列2”中所有的值都是唯一的,则不会按“列3”排序。)
- select 列 from 表 order by 列 desc;(desc降序排列“从大到小”,升序为asc“从小到大”,不过默认是升序)
order by配合limit检索
- select 列 from 表 order by 列 desc limit 数字;
where子句单一条件检索
select 列1,列2 from 表 where 列1值 = 2.50;(只返回列1值是2.50的行)
select 列1,列2 from 表 where 列1值 = 'foucs';(与字符串类型的值比较时带引号)
select 列1,列2 from 表 where 列2 between 5 and 10;(检索列2值在5到10之间的行)
select 列1,列2 from 表 where 列3 is null;(检索含空值的行)
where子句操作符: = 等于 <> 不等于 != 不等于 < 小于 <= 小于等于 > 大于 >= 大于等于 between 在指定的两个值之间
where子句多条件(and,or,in,not操作符)检索
select 列1,列2,列3 from 表 where 列4值 = ? and 列2值 <= ?;(and相当于“且”)
select 列1,列2,列3 from 表 where 列4值 = ? or 列4值 <= ?;(or相当于“或”)
select 列1,列2,列3 from 表 where 列4值 in (1001,1002) order by 列1;(in指定条件范围内)
select 列1,列2,列3 from 表 where 列4值 not in (1001,1002) order by 列1;(not取in条件范围之外)
注意:and计算次序优先级高于or,and和or同时使用时用好圆括号“()”,order by要在where后面用