對以前的一條 SQL 的總結

@zgcwkj  2020年07月31日

分類:

代碼 其它 

對以前的一條 SQL 的總結,記錄我的學習!

想想以前剛學習的時候,對 SQL 不熟悉。一個小小的需求,都想老半天。

現在回想起來,那時候是真的菜~

2017 年的需求:

CREATE TABLE `temp1` (
   `id1` int(11) NOT NULL AUTO_INCREMENT,
   `id2` int(11) DEFAULT NULL,
   PRIMARY KEY (`id1`) USING BTREE
 ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT

1596162416.jpg

以前的我:(2017)

select *
from temp1 a
where a.id2 not in (select id2 from temp1 b where b.id1 > a.id1)

要求:id1必須是自增值

現在的我:(2020)

select * from(select * from temp1 order by id1 desc) t group by id2 order by id1 asc

只需要想排序ID1,再合並ID2,就可以得到想要的結果了,甚至還能組成新的虛擬表

未來的我:期待能更好!



評論已關閉

Top