【问题标题】:Use select statement as the limit to the outer select statement使用 select 语句作为外部 select 语句的限制
【发布时间】:2019-07-23 19:21:12
【问题描述】:

为了获得表的上半部分,我设置了一个返回整数的 select 语句作为外部 select 语句的限制,但出现语法错误。

我分别检查并运行了 select 语句,它们工作正常。

我的问题是: 1.确认限制不能是另一个select语句? 2.如果上面是真的,还有什么方法可以得到表格的上半部分

select lat_n from station order by lat_n 
limit (select ceil(count(*)/2) from station);

结果:

ERROR 1064 (42000) at line 1:您的 SQL 语法有错误; 检查与您的 MySQL 服务器版本相对应的手册 在 '(select ceil(count(*)/2) from station)' 附近使用正确的语法 第 2 行

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    作为替代方案:

    select t.lat_n 
    from (
      select lat_n, @rownum:=@rownum+1 rn 
      from station, (select @rownum:=0) r
      order by lat_n
    ) t
    where t.rn <= (select count(*) from station) / 2
    

    变量@rownum 用作计数器伪列,因此仅选择表的前半行。

    【讨论】:

      【解决方案2】:

      LIMIT 接受一个或两个数字参数,它们都必须是 非负整数常量

      来自 SELECT here 的参考手册条目

      【讨论】:

      • 谢谢!之前扫描过文档,一定是瞎了眼,漏掉了常量部分!
      • 有时这些东西很容易被忽视。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 2021-01-05
      • 1970-01-01
      • 2020-03-22
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多