在数据库查询的时候,我们都是通过 select
字段来进行,它在查询中也有许多小的细节需要我们知道注意。
- select 查询关联属性文章列表:
- distinct 剔除查询结果重复行
- where 查询条件与运算符
- group by 分组
- having 条件筛选语句
- order by 排序
- limit 数据分页
优先看下面的简单使用:
mysql> show tables; +----------------+ | Tables_in_test | +----------------+ | test | +----------------+ mysql> desc test; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(20) | YES | | NULL | | | age | tinyint(4) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ mysql> select * from test; +----+------+------+ | id | name | age | +----+------+------+ | 1 | dzm | 20 | | 2 | xyq | 20 | +----+------+------+ mysql> select id, name from test; +----+------+ | id | name | +----+------+ | 1 | dzm | | 2 | xyq | +----+------+ mysql> select id as a1, name as a2 from test; +----+------+ | a1 | a2 | +----+------+ | 1 | dzm | | 2 | xyq | +----+------+
现在上面这个数据库里面只有一个 test
表,但是我依然可以通过命令行查询一个不存在的表,表名用数字代替:
mysql> select 1; +---+ | 1 | +---+ | 1 | +---+ // 这行则说明如果没字段名它会拿当前的属性作为字段名 mysql> select 2, now(); +---+---------------------+ | 2 | now() | +---+---------------------+ | 2 | 2020-09-25 16:28:50 | +---+---------------------+ // 这行则说明查询语句可以计算的 mysql> select 1+2; +-----+ | 1+2 | +-----+ | 3 | +-----+ 这行则说明很多函数都是可以在查询中使用的 round() .... mysql> select 3+4*5, 6+round(5.7); +-------+--------------+ | 3+4*5 | 6+round(5.7) | +-------+--------------+ | 23 | 12 | +-------+--------------+ 查询字段可以使用别名 mysql> select 1 as a1; +----+ | a1 | +----+ | 1 | +----+ mysql> select 1 as a1, 3+4*5 as a2, 6+round(5.7) as a3; +----+----+----+ | a1 | a2 | a3 | +----+----+----+ | 1 | 23 | 12 | +----+----+----+