doushi3454 2017-04-30 21:33
浏览 17

如何在MYSQL查询中的其他选择中进行选择?

How can I select from in other select in MYSQL query? Something like this

SET @row_number = 0;

SELECT a.num FROM

(SELECT 
    (@row_number:=@row_number + 1) AS num, id
FROM
    main) as a where a.id=6

I want to know the number of record where id=6 if it's the first row, second row or third one

please anyone can help me.

  • 写回答

1条回答 默认 最新

  • dongya6381 2017-04-30 21:38
    关注

    If your query has the filter where a.id = 6, then the row with id = 6 will always be the first row of the result set.

    I am interpreting your question to mean: "if I sorted by id ascending, what row number is the row with id = 6 going to be on". If so, you can use a simple aggregation:

    SELECT COUNT(*)
    FROM main m
    WHERE m.id <= 6;
    

    Your query seems inspired by enumerating all the rows. You could do this version as well:

    select m.*
    from (select m.*, (@rn := @rn + 1) as rn
          from main m cross join
               (select @rn := 0) params
          order by id
         ) m
    where id = 6;
    

    The first version should be more efficient, particularly with an index on id.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式