sql 分組抓取最新記錄集錦

2021-06-05 08:45:23 字數 1080 閱讀 5013

1、select * from `bookcontent` group  by book_id

bookcontent是用來存放圖書內容的乙個表,其中圖書內容是根據圖書id一章一章**的,我現在想把最新每本書更新的最新章節給抓出來,使用了如下語句:select * from `bookcontent` group  by book_id order by addtime desc,

可是這樣抓出來的結果並不是我想要的,這樣只能抓出最早插入的圖書章節記錄,怎麼才能抓出最後插入的記錄呢

補充下,假如資料表如下:

table: bookcontent

id title book_id addtime

1 a       1              2008-2-1

2 b        1             2008-3-1

3  c       1              2008-4-1

4  a       2             2008-2-5

5   b     2              2008-3-5

6   c      2             200-4-5

如何同時只抓出

3   c       1              2008-4-1

6   c      2             200-4-5

這兩條記錄

試試1、select   *   from   bookcontent  as  aaa     where   not   exists(   

select   *   from   bookcontent  where   book_id =aaa.book_id    and   addtime > a.addtime)

2、select * from bookcontent  where addtime in(select max(addtime) from bookcontent goup by book_id)

2、select * from (select * from 表 order by 最大值的那個字段 desc)

temp group by 所需分組的字段

分組取最新記錄的SQL

經常遇到這樣的情況,要取得所有客戶的最新交易記錄,讀取 所有瀏覽者最後一次訪問時間。乙個客戶只讀取最新的一次記錄,相同,大部分的人首先想 到的就是排除所有記錄,相同的只取一條。用distint,但是distint只能取到乙個欄位的值。所以使用distint就不能讀取 出所有的情況。下面是一條正確的語...

分組取最新記錄的SQL

經常遇到這樣的情況,要取得所有客戶的最新交易記錄,讀取 所有瀏覽者最後一次訪問時間。乙個客戶只讀取最新的一次記錄,相同,大部分的人首先想到的就是排除所有記錄,相同的只取一條。用distint,但是distint只能取到乙個欄位的值。所以使用distint就不能讀取 出所有的情況。下面是一條正確的語句...

SQL 分組後獲取時間為最新的記錄

1.建立一張test表,表結構如下 create table test id int 11 not null name varchar 255 not null type varchar 255 not null create time timestamp primary key id 2.插入幾條...