SQL使用要点
内连接、外连接
1.内连接是将两张表满足关联条件的数据查询出来
2.左外连接是以左表为主表拼接其他表后再根据关联条件查询出来的,左外连接只会在乎左表中的数据,不会在乎其他表是否存在对应的数据
3.右外连接是以右表为主表拼接其他表后再根据关联条件查询出来的,右外连接只会在乎右表中的数据,不会在乎其他表是否存在对应的数据
内连接
SQL语句
select * from user u, score s where u.id = s.uid;
查询结果
左外连接
SQL语句
select * from user t left join score s on t.id = s.uid;
查询结果
右外连接
SQL语句
select * from score t right join user u on t.uid = u.id;
查询结果
group by和having
用户表添加一个id相同的数据
根据用户id分组,查询占用用户id和使用相同用户id的数量
select id, count(id) quantity from user group by id;
先根据用户id分组,查询使用用户id数量大于1的用户id,再将其作为条件查询用户信息
select * from user where id in (select id from user group by id having count(id) > 1);
count函数
添加一条id为null的数据
1.count(列)时,该列不允许有null存在,否则查询结果会出现错误
2.count(主键)比count(*)性能高
根据列查询用户数量
select count(id) quantity from user;
根据*查询用户数量
select count(*) quantity from user;
select * from存在的问题
1.不管需要与否都会从数据库表中拿到所有字段的数据,会导致查询低效
2.如果关联多张表,可能存在字段名相同的字段,从而影响数据的绑定
3.改写成select 字段名 from可以降低数据传输量,从而提升性能
insert into 表名时需要注意的问题
不推荐使用insert into 数据库表名 values ('值', ...),因为如果当数据库表字段发生变化时无法精准写入数据到对应的字段中
规范的添加语句写法: insert into 数据库表名 (字段名, ...) values ('值', ...)