sql语法

基本操作

查表

select * from media where source like "新华社" order by time desc limit 20;
  • oder by time desc 降序
  • limit
  • 字符串匹配,like;模糊"%新华%"

如何去重插入

设置主键

alter table media add primary key (title,source,time);
alter table media add primary key (url);

删除主键:alter table media drop primary key;

去重插入

insert ignore+xx

MySQL避免插入重复记录的方法

SQL语句删除表、清空表

语法: DROP TABLE <表名>;

示例: -- 删除学生表
DROP TABLE Student;

清空表: TRUNCATE TABLE <表名>;

示例:-- 删除学生表
TRUNCATE TABLE Student;

创建表、查看表、表项

CREATE TABLE table_name (column_name column_type);创建列表。
show tables;查看数据表。
desc testnews;查看数据表testnews的列名。

复杂操作

多表联合查询:union[all],intersect,minus

 union :得到两个查询结果的并集,并且自动去掉重复行。不会排序

 union all:得到两个查询结果的并集,不会去掉重复行。也不会排序

 intersect:得到两个查询结果的交集,并且按照结果集的第一个列进行排序

 minus:得到两个查询结果的减集,以第一列进行排序

union all是concatenate,union是全部去重的结果。

select DISTINCT * from (select xm,province,city,born,sex  from people_network_100 UNION ALL select xm,province,city,born,sex  from people_network_5000 UNION ALL select xm,province,city,born,sex  from people_network_xukai UNION ALL select xm,province,city,born,sex  from people_network_onestage_rand) union_table
select * from (select xm,province,city,born,sex  from people_network_100 UNION select xm,province,city,born,sex  from people_network_5000 UNION select xm,province,city,born,sex  from people_network_xukai UNION select xm,province,city,born,sex  from people_network_onestage_rand) union_table 
#所有Union all改为union,并不加distinct,结果一样

多表连接查询

多表连接暂存

select distinct 去重查询

select count(distinct xm,province,city,born,sex)  from people_network_100


1w的people_network_100实际去重后,有人节点3千多。

因为Union可以去重,去重查询的等价表示(使用多表并集):

# 自己与自己去重并集
select count(*) from (select xm,province,city,born,sex  from people_network_100 union select xm,province,city,born,sex  from people_network_100) union_table
#它与下面的使用普通distinct的嵌套查询等价
select count(*) from (select distinct xm,province,city,born,sex  from people_network_100 ) table_r

在查询结果中再查询

select count(*) from (select xm,province,city,born,sex  from people_network_100 UNION select xm,province,city,born,sex  from people_network_5000 UNION select xm,province,city,born,sex  from people_network_xukai UNION select xm,province,city,born,sex  from people_network_onestage_rand) union_table

在结果表中再查询时,注意:这里每一个导出表必须起一个别名,否则会报错。 1248 - Every derived table must have its own alias

  • 可以继续嵌套:
select count(*) from (select distinct union_table.xm,union_table.province,union_table.city,union_table.born,union_table.sex from (select xm,province,city,born,sex  from people_network_100 UNION select xm,province,city,born,sex  from people_network_5000 UNION ALL select xm,province,city,born,sex  from people_network_xukai UNION ALL select xm,province,city,born,sex  from people_network_onestage_rand) union_table) table_2

posted @ 2021-02-27 21:26  zae  阅读(88)  评论(0)    收藏  举报