建一張表以下:表名爲 numbermysql
select * from number where id in ( select distinct n1.id from number n1,number n2,number n3 where (n1.num = n2.num and n2.num = n3.num and ( (n1.id + 1= n2.id and n2.id +1 = n3.id)or (n3.id + 1= n2.id and n2.id +1 = n1.id)or (n3.id + 1= n1.id and n1.id +1 = n2.id) ) ) order by n1.id )
運行結果:sql
思想:將上表中的數據分組取最小。微信
select min(id) as minid,id,num from ((select * from number where id in ( select distinct n1.id from number n1,number n2,number n3 where (n1.num = n2.num and n2.num = n3.num and ( (n1.id + 1= n2.id and n2.id +1 = n3.id)or (n3.id + 1= n2.id and n2.id +1 = n1.id)or (n3.id + 1= n1.id and n1.id +1 = n2.id) ) ) order by n1.id ))as t) group by num ;
運行結果:學習
原表中的數據以下:spa
/* 方法一: 1.建立臨時表 2.將須要的數據保存到臨時表 3.清空原表,將臨時表中的數據保存到原表中 4.刪除臨時表 */ create temporary table temp select min(id),email from test group by email; truncate table test; insert into test select * from temp; select * from test; drop table temp; /* 方法二: 1.按照郵件分組,把每一組中的最小的id取出放在臨時表中 2.刪除原表中除臨時表中id之外的其餘id 對應的數據 */ create temporary table temp select min(id) as minid from test group by email; delete from test where id not in (select minid from temp); drop table temp; /* 方法三: 在原表上操做 */ delete from test where id not in ( select minid from ( select min(id) minid from test group by email )b ); select * from test;
運行結果:3d
建立兩張表,表明兩個店鋪,每一個店鋪有不一樣的,每一個櫃檯賣不一樣的商品。code
/* 兩個商店,每一個店有不一樣的櫃檯,每一個櫃檯上賣有不一樣的商品 */ create table tableA( id int(10) not null primary key auto_increment, monorail varchar(20), variety varchar(50) ); insert into tableA values (1,'a1','蘋果'),(2,'a1','梨'),(3,'a3','香蕉'),(4,'a4','蘋果'),(5,'a5','西瓜'), (6,'a6','蘋果'),(7,'a7','葡萄'),(8,'a8','桃子'); create table tableB( id int(10) not null primary key auto_increment, monorail varchar(20), variety varchar(50) ); insert into tableB values (1,'b1','蝦'),(2,'b2','豬肉'),(3,'b3','蘋果'),(4,'b4','西瓜'),(5,'b5','梨'), (6,'b6','香蕉');
兩個表數據以下:blog
’rem
/* 內鏈接,查處兩個商店共有的商品 */ select * from tablea A INNER JOIN tableb B on A.variety = B.variety ;
運行結果io
/* 左鏈接,以A表爲左表 */ select * from tablea A LEFT JOIN tableb B on A.variety = B.variety ;
運行結果
/* 右鏈接,以A表爲左表 */ select * from tablea A RIGHT JOIN tableb B on A.variety = B.variety ;
運行結果
/* 左外鏈接,以A表爲左表 */ select * from tablea A LEFT JOIN tableb B on A.variety = B.variety Where B.variety is null;
運行結果
/* 右外鏈接,以A表爲左表 */ select * from tablea A RIGHT JOIN tableb B on A.variety = B.variety Where A.variety is null;
運行結果
mysql不支持full (outer) join 故使用union代替
/* 全鏈接 */ select * from tablea A LEFT JOIN tableb B on A.variety = B.variety ; union select * from tablea A RIGHT JOIN tableb B on A.variety = B.variety ;
運行結果
select * from tablea A LEFT JOIN tableb B on A.variety = B.variety Where B.variety is null union select * from tablea A RIGHT JOIN tableb B on A.variety = B.variety Where A.variety is null
運行結果
歡迎掃碼關注個人微信公衆號,或者微信公衆號直接搜索Java傳奇,不定時更新一些學習筆記!