SQL 最後()
LAST() 函數
LAST() 函數傳回指定的欄位中最後一個記錄的值。
SQL LAST() 語法
SELECT LAST(column_name) FROM table_name;
註解:只有MS Access 支援LAST () 函數。
SQL Server、MySQL 和Oracle 中的SQL LAST() 工作區
SQL Server 語法
SELECT TOP 1 column_nameFROM table_name
ORDER BY column_name DESC;
ORDER BY column_name DESC;
實例
SELECT TOP 1 name FROM Websites
ORDER BY id DESC;
ORDER BY id DESC;
MySQL 文法
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1;
ORDER BY column_name DESC
LIMIT 1;
實例
SELECT name FROM Websites
ORDER BY id DESC
LIMIT 1;
ORDER BY id DESC
LIMIT 1;
Oracle 語法
SELECT column_name FROM table_name
ORDER BY column_name DESC
WHERE ROWNUM <=1;
ORDER BY column_name DESC
WHERE ROWNUM <=1;
範例
SELECT name FROM Websites
ORDER BY id DESC
WHERE ROWNUM <=1;
ORDER BY id DESC
WHERE ROWNUM <=1;
示範資料庫
在本教學中,我們將使用 php 樣本資料庫。
下面是選自"Websites" 表的資料:
+----+--------------+--- ------------------------+-------+---------+
| id | name | url | alexa | country |
+----+----------+------------------------------------ --------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA | 1 |
| 2 | 淘寶 | https://www.taobao.com/ | 13 | CN cn/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 ://www.facebook.com/ | 3 | USA |
| 6 | 百度| https://www.baidu.com/ | 4 | CN |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---- -----------+-----------------------------------------+-------+-- -------+
| id | name | url | alexa | country |
+----+----------+------------------------------------ --------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA | 1 |
| 2 | 淘寶 | https://www.taobao.com/ | 13 | CN cn/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 ://www.facebook.com/ | 3 | USA |
| 6 | 百度| https://www.baidu.com/ | 4 | CN |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---- -----------+-----------------------------------------+-------+-- -------+
下面的SQL 語句選取"Websites" 表的"name" 欄位中最後一個記錄的數值:
實例SELECT name FROM Websites
ORDER BY id DESCLIMIT 1;
執行上述SQL 結果如下:
執行上述SQL 結果如下: