查找表中多余的重復記錄,重復記錄是根據單個字段(peopleId)來判斷select * from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
例如:
產品參數表rule_product_info 同一個申請單是否有多條記錄
用select app_no,count(1) from rule_product_info group by app_no having count(1)>1
2、刪除表中多余的重復記錄,重復記錄是根據單個字段(peopleId)來判斷,只留有rowid最小的記錄delete from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)
3、查找表中多余的重復記錄(多個字段)
select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
4、刪除表中多余的重復記錄(多個字段),只留有rowid最小的記錄
delete from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)
5、查找表中多余的重復記錄(多個字段),不包含rowid最小的記錄
select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)
(二)比方說
在A表中存在一個字段“name”,
而且不同記錄之間的“name”值有可能會相同,
現在就是需要查詢出在該表中的各記錄之間,“name”值存在重復的項;
Select Name,Count(*) From A Group By Name Having Count(*) > 1
如果還查性別也相同大則如下:
Select Name,sex,Count(*) From A Group By Name,sex Having Count(*) > 1
COUNT(*) 函數返回在給定的選擇中被選的行數。
語法:SELECT COUNT(*) FROM table
使用:現在有一個表,名叫app_category,從Navicat中可以看到表中所有數據,如圖所示,可見表中有297條數據
使用count函數的時候可以看到:
當然僅僅是這個樣子,是木有意義的,我用個可視化工具一眼看穿,要這個函數就顯得雞肋了,那么我們繼續往下看。
場景是這樣的:表app_category與表category關聯。且表間關系是一對多,即同一個app_category_id 對應多個category-id,現在我需要統計出每一個category_id在app_category表中出現的次數那么該如何實現呢,請看接下來的操作:
這樣依然有點不夠酷炫,那么我們還可以在后面繼續追加sql語句呀
例如這條語句:
SELECT category_id ,COUNT(*) AS count FROM app_category
GROUP BY category_id HAVING count(category_id) >2
其查詢的結果是只有count的值大於2 的時候,才是需要的結果
是不是有點小先進了,當然不要激動,我們還可以把這個查詢的結果作為子查詢,進行嵌套查詢,兩個表關聯查詢然后再嵌套查詢等等。這里我就不過多截圖,上一個開發商城項目中用到的查詢語句:
SELECT ps.name FROM property_set ps , category_property_set cps WHERE ps.id=cps.property_set_id AND category_id=(
SELECT category_id AS count FROM category_property_set
GROUP BY category_id HAVING count(category_id) <5
)
大眼一看,可能比較懵逼,聽我分析一下:
首先是子查詢:SELECT category_id AS count FROM category_property_set
GROUP BY category_id HAVING count(category_id) <5
查出category_property_set 表中category_id出現次數小於5的那個category_id的具體的值,剛好得到的結果是只有一條,那么滿足嵌套查詢的條件,用到<,>=等符號時,子查詢結果必須唯一,所有給其添加到外部查詢,其實等價於這樣一條語句:
SELECT ps.name FROM property_set ps , category_property_set cps WHERE ps.id=cps.property_set_id AND category_id=925640926728343552
不用懷疑,這個category_id就是查詢出來的ID,然后這又是一個最最基本的兩表聯合查詢,連個外聯內聯都沒用,然后結果就是這個樣子