mysql中,查询一般有哪些

如题所述

第1个回答  2019-05-09
单表查询:
查询全部字段数据:select * from tablename;
查询某字段(一列)的值:select column_name from tablename;
where条件查询:select column_name frome tablename where 表达式(查询条件,eg:id=1)
多表查询:
联合查询,连接查询(内连接,左外连接,右外连接)。
联合查询:union 将两个sql查询的结果集合并在一个表中。
注意:两个结果集的表结构相同。
select student_name from student where s_id = 1
union
select teacher_name from teacher where t_id = 3;
注意:默认删除重复,union all 允许重复值。
链接查询:
内连接:inner join (等同于join)
select s.s_name,t.t_name from student s inner join teacher t on s.s_id = t.s_id;
可以不使用inner join
select s.s_name,t.t_name from student s ,teacher t where s.s_id = t.s_id;
使用场景:查询A 表和B表同时满足查询条件的数据,
左外连接: left join
select s.s_name,t.t_name from student s left join teacher t on s.s_id = t.s_id;
使用场景:查询A表的所有满足条件的数据,B表中有满足条件的则记录,若没有,补为null值。
手册原话:从左表 (student) 那里返回所有的行,即使在右表 (teacher) 中没有匹配的行。
右外连接: right join
select s.s_name,t.t_name from student s right join teacher t on s.s_id = t.s_id;
使用场景:查询B表的所有满足条件的数据,A表中有满足条件的则记录,若没有,补为null值。
手册原话:从右表 (teacher) 那里返回所有的行,即使在左表 (student) 中没有匹配的行。

子查询:在sql语句中,包含另一个sql语句的查询,被包含的sql语句为子查询。
select student_grade from grade where student_id = (select student_id from student where name=’张三’);
使用场景: 一般不提倡写子查询,这样会降低数据库的效率。
在优化数据库时,尽量减少子查询。本回答被网友采纳
第2个回答  2019-05-09
单表查询,联合查询,还有嵌套查询
相似回答