在mysql中,如果要查询数据,需要使用select语句。
查询指定列
select <列名1>, <列名2>, …
from <表名>;
比如之前,在我们之前创建的Student表中,同时查询出名字和生日
select name, birth
from Student;
查询所有列
select *
from <表名>;
此处*代表全部的意思,会按照创建数据表的顺序将所有列全部查询出来。
为列起别名
select <列1> as <别名1>, <列2> as <别名2>, <列3> as <别名3>
from <表名>;
比如说,重新用起别名的方式查询名字和生日
select name as 姓名, birth as 生日
from Student;
消除重复的列
使用distinct可以消除重复列
select distinct <列1>, <列2>, …
from <表名>;
比如,对性别消除重复,查看有几个类别
select distinct gender
from Student;
查询指定条件的列
通过where子句添加条件,可以查询指定列
select <列1>, <列2>, …
from <表名>
where <条件>;
比如说,查询id为1的学生的姓名和生日
select name, birth
from Student
where id = 1;
不使用from创建特殊的select语句
一般来说,select语句都是需要配合from一起使用的,这样才能够从数据表中查询数据。
但是事实上,在mysql中,没有规定select必须和from一起使用。它可以单独使用,比如说
select '2021-11-11' as 日期;
但是这种情况是非常罕见的,因为这样使用的实际意义很有限。