仅在mysql查询中获取第一行

仅在mysql查询中获取第一行

本文介绍了仅在mysql查询中获取第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个查询,例如

if i had a query such as

select * from tbl_foo where name = 'sarmen'

并且此表具有多个name = sarmen实例,我如何在不创建自动递增列的情况下虚拟地为每行分配行号?我有一个即时消息的原因,在我的示例中不需要auto_incrimented col.

and this table has multiple instances of name = sarmen how can i virtually assign row numbers to each row without having to create a column that auto incriments? i have a reason for what im doing and dont need an auto_incrimented col in my example.

因此,如果通过sql或php为每行分配一个虚拟行号,我将可以在需要时随时打印出第一行或最后一行.

so if each row is assign a virtual row number through sql or maybe php i will be able to print out the first row or the last row anytime i need to.

thnx

推荐答案

仅返回一行,请使用LIMIT 1:

SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1

除非您具有ORDER BY子句,否则说第一行"或最后一行"是没有意义的.假设您添加了ORDER BY子句,则可以通过以下方式使用LIMIT:

It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY clause. Assuming you add an ORDER BY clause then you can use LIMIT in the following ways:

  • 要获取第一行,请使用LIMIT 1.
  • 要获取第二行,可以使用带有偏移量的limit:LIMIT 1, 1.
  • 要获取最后一行的顺序(将ASC更改为DESC,反之亦然),请使用LIMIT 1.
  • To get the first row use LIMIT 1.
  • To get the 2nd row you can use limit with an offset: LIMIT 1, 1.
  • To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1.

这篇关于仅在mysql查询中获取第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 22:28