[英]Passing value to LIMIT function using SELECT query
There is a table named STATION.有一个名为 STATION 的表。
I want to display half rows of the table.
我想显示表格的半行。
MYSQL query
MYSQL查询
SELECT *
FROM STATION
LIMIT (SELECT COUNT(ID) FROM STATION)/2
I tried to perform a query like this but I am getting syntax error.我尝试执行这样的查询,但出现语法错误。
What is wrong in this query?这个查询有什么问题?
How can I perform this query?如何执行此查询?
One method is to use window functions:一种方法是使用 window 函数:
select t.*
from (select t.*,
ntile(2) over (order by id) as tile
from t
) t
where tile = 1;
I have never seen a need of querying exactly half the table.我从来没有见过需要查询正好一半的表。 If you are asking this out of curiosity, that's fair but if there is really a need where you are trying to implement something like this, please revisit the design.
如果您出于好奇而问这个问题,那是公平的,但如果您确实需要尝试实现类似的东西,请重新审视设计。
Coming to your question, you can possibly do two things:谈到你的问题,你可以做两件事:
Implement a stored procedure and query the count and store in a variable and then pass it on to the actual SELECT query for the LIMIT clause.实现一个存储过程并查询计数并存储在一个变量中,然后将其传递给实际的 SELECT 查询 LIMIT 子句。
From your client code fire 2 different queries - 1 for count and calculate half (non fraction) and then pass it to the limit clause of next select query.从您的客户端代码触发 2 个不同的查询 - 1 个用于计数和计算一半(非分数),然后将其传递给下一个 select 查询的限制子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.