MySQL SQL First() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15570665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:01:00  来源:igfitidea点击:

SQL First() Function

mysqlsql

提问by gmustudent

I am using phpMyAdmin to write some SQL code that I thought was simple but proving to be a headache. I'm using thistutorial to help me out. My goal is to get the first and last columns id's from a result set. When I do this query I get 5 rows starting at 15 and going through 11.

我正在使用 phpMyAdmin 编写一些我认为很简单但事实证明很头疼的 SQL 代码。我正在使用教程来帮助我。我的目标是从结果集中获取第一列和最后一列 id。当我执行此查询时,我得到 5 行,从 15 开始到 11。

SELECT id
FROM boardPost
WHERE recipientId = 1
ORDER BY id DESC
LIMIT 0,5

However, when I try this query I get an error #1064: "You have an error in your SQL syntax."

但是,当我尝试此查询时,我收到错误 #1064:“您的 SQL 语法有错误。”

SELECT FIRST(id)
FROM boardPost
WHERE recipientId = 1
ORDER BY id DESC
LIMIT 0,5

采纳答案by a_horse_with_no_name

Something like this maybe?

也许像这样的东西?

SELECT min(id), max(id)
from (
  select id
  from boardPost
  where recipientId = 1
  order by id desc
  limit 0,5
) t

回答by Guido Hendriks

If you just want the first and the last idof a result set, you could consider this:

如果您只想要id结果集的第一个和最后一个,您可以考虑:

SELECT MIN(id) firstId, MAX(id) lastId FROM someTable WHERE aField = 1;

Note that it'll only work if you do use and ORDER BYan AUTO_INCREMENTfield, else you might get unexpected results.

请注意,如果你使用它只会工作,并ORDER BYAUTO_INCREMENT现场,否则你可能会得到意想不到的效果。

It'll only work with the full set. If you need the first and last idof a limited one, you're probably better of using 2 queries with ASCand DESCorder and LIMIT 1.

它只适用于全套。如果您需要id有限的第一个和最后一个,您可能最好使用 2 个查询ASCDESCorder 和LIMIT 1

回答by John Conde

MySQL does not support the FIRST()function. You will need to use the workaround they specified in that tutorial (using ORDER BYand LIMIT)

MySQL 不支持该FIRST()功能。您将需要使用他们在该教程中指定的解决方法(使用ORDER BYLIMIT

回答by diego10

I think that is what you want?

我想这就是你想要的?

Select id from boardPost order by id asc limit 1

and

Select id from boardPost order by id desc limit 1

回答by ashleedawg

In some situations (like mine, that first brought me here), there are some rarely-used MySQL "windowing functions"such as FIRST_VALUEand LAST_VALUEthat may provide the functionality you're seeking.

在某些情况下(比如我的,第一次把我带到这里),有一些很少使用的 MySQL “窗口函数”,例如FIRST_VALUELAST_VALUE可能提供您正在寻找的功能。

(Here's more info on Window Function Concepts and Syntax, and the Wikipedia descriptionof the term.)

(这里有更多关于Window Function Concepts and Syntax 的信息,以及该术语的维基百科描述。)