简体   繁体   English

关于数据库查询的简单问题

[英]Simple question on database query

I have been asked in an interview to write a SQL query which fetches the first three records with highest value on some column from a table. 我在一次采访中被要求编写一个SQL查询,该查询从表的某个列中获取具有最高值的前三个记录。 I had written a query which fetched all the records with highest value, but didn't get how exactly i can get only first three records of those. 我写了一个查询,该查询获取了所有具有最高价值的记录,但没有确切地知道我只能得到那些记录的前三个记录。

Could you help me in this. 你能帮我这个忙吗?

Thanks. 谢谢。

SELECT TOP 3 * FROM Table ORDER BY FieldName DESC

From here , but might be a little out of date: 这里开始 ,但可能有点过时了:

Postgresql: PostgreSQL的:

SELECT * FROM Table ORDER BY FieldName DESC LIMIT 3

MS SQL Server: MS SQL Server:

SELECT TOP 3 * FROM Table ORDER BY FieldName DESC

mySQL: MySQL的:

SELECT * FROM Table ORDER BY FieldName DESC LIMIT 3

Depending on the database engine, either 取决于数据库引擎,

select top 3 * from table order by column desc

or 要么

select * from table order by column desc limit 3

选择顶部3 ....

The syntax for TOP 3 varies widely from database to database. 对于每个数据库,TOP 3的语法差异很大。

Unfortunately, you need to use those constructs for the best performance. 不幸的是,您需要使用这些构造来获得最佳性能。 Libraries like Hibernate help here, because they can translate a common API into the various SQL dialects. 像Hibernate这样的库在这里可以提供帮助,因为它们可以将通用的API转换为各种SQL方言。

Since you are asking about Java, it is possible to just SELECT everything from the database (with an ORDER BY), but just fetch only the first three rows. 由于您正在询问Java,因此可以仅选择数据库中的所有内容(使用ORDER BY),而仅获取前三行。 Depending on how the query needs to be executed this might be good enough (especially if no sorting on the database has to happen thanks to appropriate indexes, for example when you sort by primary key fields). 根据查询的执行方式,这可能就足够了(尤其是如果由于适当的索引而不必在数据库上进行排序,例如当您按主键字段进行排序时)。

But in general, you want to go with an SQL solution. 但总的来说,您想使用SQL解决方案。

In oracle you can also use where rownum < 4... 在oracle中,您还可以使用where rownum <4 ...

Also on mysql there is a Limit keyword (i think) 另外在mysql上有一个Limit关键字(我认为)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM