Mysql选择查询直到达到条件

时间:2016-07-13 14:46:53

标签: mysql conditional-statements limit

假设我的用户表中有用户列表,如下所示。我需要找到我桌上的用户数,直到userid等于 100

所以答案是(3)。但我怎么能发现这是MySQL查询。有什么想法吗?

userid    name
---------------
10        aaa
30        bbb
100       ccc
60        ddd

2 个答案:

答案 0 :(得分:1)

这是实现您期望的工作之一。

SET @row_number:=0;

SELECT A.row_number FROM (
    SELECT Userid, name, @row_number:=@row_number+1 AS row_number  
    FROM UserDetail
) AS A
WHERE A.Userid = 100;

Working DEMO

如果UserId不是唯一ID并且可以重复,则可以添加ORDER BY LIMIT 1

SET @row_number:=0;

SELECT A.row_number FROM (
    SELECT Userid, name, @row_number:=@row_number+1 AS row_number  
    FROM UserDetail
) AS A
WHERE A.Userid = 100
ORDER BY A.row_number
LIMIT 1;

Working DEMO

使用给定数据执行示例:

--DROP TABLE UserDetail;

CREATE TABLE UserDetail (Userid INT,  name VARCHAR (50));

INSERT INTO UserDetail (Userid, name) VALUES
(10 , 'Aaa'),
(30 , 'Bbb'),
(100, 'Ccc'),
(60 , 'ddd');

SET @row_number:=0;

SELECT A.row_number FROM (
    SELECT Userid, name, @row_number:=@row_number+1 AS row_number  
    FROM UserDetail
) AS A
WHERE Userid = 100;

答案 1 :(得分:0)

这在MySql中很难做到,因为数字的“第一个”实例很难确定。

解决此问题的一种方法是创建行号,然后选择Userid = 100的最小行号

fun1 <- function(x){ifelse(sign(head(x,1))== sign(tail(x,1)),  "no",
                           ifelse(sign(head(x,1))==-1 & sign(tail(x,1))==1, "OPDV",
                                  ifelse(sign(head(x,1))==1 & sign(tail(x,1))==-1,"CLDV","no")))}

Here is a functional example