具有多条记录的 MySQL“SELECT LIMIT 1”是否从顶部选择第一条记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17517246/
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 18:04:56  来源:igfitidea点击:

Does MySQL "SELECT LIMIT 1" with multiple records select first record from the top?

mysqlselectlimit

提问by hammus

I've searched and searched and can't find an answer to this question, I'm probably asking it in the wrong way.

我搜索了又搜索,但找不到这个问题的答案,我可能问错了。

I am querying an employee database.

我正在查询员工数据库。

I need to get details based on a position id, however there could be multiple records for that position id as this organisation has permanent employees and temporary employees that act against the same position.

我需要根据职位 id 获取详细信息,但是该职位 id 可能有多个记录,因为该组织有针对同一职位的固定员工和临时员工。

So, in order to get the CURRENT occupant of the position id, I need my query to SELECT the FIRST record that matches the position string, from the the TOP DOWN.

因此,为了获取位置 id 的当前占用者,我需要我的查询从 TOP DOWN 中选择与位置字符串匹配的第一个记录。

will this select the first matched record from the top?

这会从顶部选择第一个匹配的记录吗?

SELECT * WHERE `position_id`="00000000" LIMIT 1;

Thanks in advance.

提前致谢。

采纳答案by apartridge

You need an ORDER BYclause to define the ordering between the individual records your table. If you do not use ORDER BYyou can assume no fixed order between the records, and you could get a new order each time you executed the query.

您需要一个ORDER BY子句来定义表中各个记录之间的排序。如果不使用ORDER BY,则可以假设记录之间没有固定顺序,并且每次执行查询时都可以获得新顺序。

回答by flogvit

From the manual:

从手册:

With one argument, the value specifies the number of rows to return from the beginning of the result set

带一个参数,该值指定从结果集的开头返回的行数

So with LIMIT 1you get the first row from the result set. What the result set is depends on engine used and which indexes you have. If you want the first row added, you need to create another column to define that.

所以LIMIT 1你从结果集中得到第一行。结果集是什么取决于使用的引擎和您拥有的索引。如果要添加第一行,则需要创建另一列来定义它。

回答by GolezTrol

It just gets one at random*. There's no way to tell which one it will be, unless you add an ORDER BYclause.

它只是随机获取一个*。除非您添加ORDER BY子句,否则无法确定它将是哪一个。

*Not really at random, of course. It depends on the way the records are stored and repeated queries will probably return the same result every time, at least as long as you don't modify the table or its contents. I actually mean, you cannot be sure.

*当然,并不是真的随机。这取决于记录的存储方式,重复查询可能每次都返回相同的结果,至少只要您不修改表或其内容。我的意思是,你不能确定。