SQL中的 FIRST() 函数返回指定的列中第一个记录的值
SELECT FIRST(column_name) FROM table_name;
注意
只有 MS Access 支持 FIRST() 函数
虽然其它数据库中没有实现该函数,不过我们我们可以使用 LIMIT 语句达到同样的效果
SQL Server、MySQL 和 Oracle 中的 SQL FIRST() 实现
1、 SQLServer;
SELECT TOP 1 column_name FROM table_name;
例如
SELECT TOP 1 lession_name FROM lession_views ORDER BY views DESC;
2、 MySQL;
SELECT column_name FROM table_name LIMIT 1;
例如
SELECT lession_name FROM lession_views ORDER BY views DESC LIMIT 1;
3、 Oracle;
SELECT column_name FROM table_name WHERE ROWNUM <=1;
例如
SELECT lession_name FROM lession_vies ORDER BY views DESC WHERE ROWNUM <=1;
演示数据
先在 MySQL 数据库运行下面的语句创建测试数据
CREATE DATABASE IF NOT EXISTS ddkk default character set utf8mb4 collate utf8mb4_unicode_ci;
USE ddkk;
DROP TABLE IF EXISTS lession;
CREATE TABLE lession (
id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(32) default '',
views int(11) NOT NULL default '0',
created_at DATETIME
);
INSERT INTO lession(id,name,views,created_at) VALUES
(1, 'Python DDKK.COM 弟弟快看',981,'2017-04-18 13:52:03'),
(2, 'Scala DDKK.COM 弟弟快看',73,'2017-04-18 16:03:32'),
(3, 'Ruby DDKK.COM 弟弟快看',199,'2017-05-01 06:16:14');
使用SELECT * FROM lession; 运行结果如下
+----+---------------------+-------+--------------------+
| id | name | views | created_at |
+----+---------------------+-------+--------------------+
| 1 | Python DDKK.COM 弟弟快看 | 981 | 2017-04-18 13:52:03 |
| 2 | Scala DDKK.COM 弟弟快看 | 73 | 2017-04-18 16:03:32 |
| 3 | Ruby DDKK.COM 弟弟快看 | 199 | 2017-05-01 06:16:14 |
+----+---------------------+-------+--------------------+
总共有3 条记录
范例
下面的SQL 语句读取 lession 表中浏览量最多的课程 ( lession_name )
SELECT name FROM lession ORDER BY views DESC LIMIT 1;
运行结果如下
mysql> SELECT name FROM lession ORDER BY views DESC LIMIT 1;
+---------------------+
| name |
+---------------------+
| Python DDKK.COM 弟弟快看 |
+---------------------+