正好想寫一條刪除重復語句并保留一條數據的SQL选脊,網上查了一部分資料寫的很詳細,但還是在這里寫下自己的理解脸甘,以遍后續(xù)學習 恳啥。如下:
表字段和數據:
SQL語句:?
DELETE FROM `user` WHERE id NOT IN(SELECT * FROM(SELECT id FROM `user` GROUP BY username)AS b)? 臨時表
理解:
先從里面的SQL開始看
1、SELECT id FROM `user` GROUP BY username ?根據名字分組查詢出每組的ID丹诀。
2角寸、SELECT * FROM(SELECT id FROM `user` GROUP BY username) AS b ?這句話中有2個疑問點,
? 第一忿墅、為什么要套這樣一個select?因為 更新數據時使用了查詢沮峡,而查詢的數據又做更新的條件疚脐,mysql不支持這種方式
? ? 如果不套上這個select查詢,那么將會報1093 - ?You can't specify target table 'user' for update in FROM clause錯誤邢疙。
第二棍弄、這句話中一定要取別名,不然會報1248 -?Every derived table must have its own alias 錯誤
3疟游、結合上面的分析來看一下整個的SQL語句理解呼畸,先將分組的ID查出來,然后刪除USER表中ID 不在分組ID中的數據颁虐,那么就實現效果了蛮原。
delete from 表名 where ?ID not in (select * from (select ?id from 表名 group by 分組的列名) ? 別名)
效果如下:
print('MySQL數據庫正在連接,請稍等另绩。儒陨。。笋籽。蹦漠。。')
db= pymysql.connect('27.255.79.21','user','*******','db_qishu',charset="utf8")
#db = pymysql.connect('127.0.0.1', 'root', 'root', 'db_qishu', charset="utf8")
cursor= db.cursor()
print('MySQL數據庫已經連接3岛!5言啊!!Q忻埋同!')
#sql = "SELECT Novel_url,count(Novel_url) as count FROM qishu_books_sort08 GROUP BY Novel_url HAVING count(Novel_url)>1 ORDER BY count ASC;"
#sql = "select Novel_url,count(*) as count from qishu_books_sort08 group by Novel_url having count>1;"? #120704
#sql = "select Novel_ID,Novel_title from qishu_books_sort08 where Novel_url in (select Novel_url from qishu_books_sort08 group by Novel_url having count(Novel_url)>1) ORDER BY Novel_ID ASC;"
#sql = "SELECT Novel_url as count FROM qishu_books_sort011 GROUP BY Novel_url ORDER BY count ASC;"
#sql = "select Novel_ID from qishu_books_sort08 group by Novel_url having count(Novel_url) > 1;"
sql= "SELECT Novel_ID FROM `qishu_books_sort08` GROUP BY Novel_url ORDER BY Novel_ID ASC;"
cursor.execute(sql)
TXT_list= cursor.fetchall()
print(TXT_list)
print(len(TXT_list))
mysql可以根據字段進行排序
其中,DESC表示降序蚜印,ASC表示升序
order by 字段名? DESC;按照字段名降序排序
order by 字段名 ASC;按照字段名升序排序