【问题标题】:MySql: Get number of row from query where id matchesMySql:从查询中获取id匹配的行数
【发布时间】:2017-01-13 15:12:16
【问题描述】:

我有一个复杂的选择,例如:

select id from table
  left join...
  left join... (a lot of joins)
where ... (a lot of ANDs and ORs)
order by... (a lot of orders)

我得到如下结果:

1234
5565
7212
2212
etc.

我有一个属于结果集的 id,例如 7212,并且想知道结果集中的哪一行与该 id 匹配(从第 0 行开始,在我的示例中为第 2 行)。

现在我正在读取所有数据并在 php 中进行比较,但我想知道是否有一个 SQL 语句可以为我执行此操作并在输入 7212 时结果为 2。

事实上,我想获取前一个和下一个 id(第 1 行和第 3 行 = 5565 和 2212),如果在 1 个查询中以某种方式可能会更好。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    您可以选择数字行:

    select @rownum:=@rownum+1 No, foo, bar from table, (SELECT @rownum:=0) r;
    

    这可能与此处提出的问题重复:How to show sequential number in MySQL query result

    【讨论】:

      【解决方案2】:

      为每个选定的行添加一个 auto_increment 索引:

      SELECT  
          @i:=@i+1 as index, 
          id 
      FROM table, (SELECT @i:= 0) AS i
          LEFT JOIN...
          LEFT JOIN...(a lot of joins)
      WHERE ... (a lot of ANDs and ORs)
      ORDER BY... (a lot of orders)
      

      给你这个:

      index id
      1     1234
      2     5565
      3     7212
      4     2212
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多