计算和限制每个字段值的行数不起作用

时间:2017-05-31 19:08:15

标签: mysql sql phpmyadmin xampp

我试图限制给定查询的每个字段值的行数。我发现了这个问题:

here

与链接的第一个答案一样,我创建了下表:

create table mytab (
    id int not null auto_increment primary key,
    first_column int,
    second_column int
) engine = myisam;

插入此数据:

insert into mytab (first_column,second_column) values 
    (1,1),
    (1,4),
    (2,10),
    (3,4),
    (1,4),
    (2,5),
    (1,6);

最后运行此查询

select
    id,
    first_column,
    second_column,
    row_num
from 
    (select 
        *,
        @num := if(@first_column = first_column, @num + 1, 1) as row_num,
        @first_column:=first_column as c
    from mytab 
    order by first_column,id) as t,
    (select @first_column:='',@num:=0) as r;

但是,只要重复 first_column ,row_num会增加,而不是获得此结果,

+----+--------------+---------------+---------+
| id | first_column | second_column | row_num |
+----+--------------+---------------+---------+
|  1 |            1 |             1 |       1 |
|  2 |            1 |             4 |       2 |
|  5 |            1 |             4 |       3 |
|  7 |            1 |             6 |       4 |
|  3 |            2 |            10 |       1 |
|  6 |            2 |             5 |       2 |
|  4 |            3 |             4 |       1 |
+----+--------------+---------------+---------+

我得到了这个结果:

+----+--------------+---------------+---------+
| id | first_column | second_column | row_num |
+----+--------------+---------------+---------+
|  1 |            1 |             1 |       1 |
|  2 |            1 |             4 |       1 |
|  5 |            1 |             4 |       1 |
|  7 |            1 |             6 |       1 |
|  3 |            2 |            10 |       1 |
|  6 |            2 |             5 |       1 |
|  4 |            3 |             4 |       1 |
+----+--------------+---------------+---------+

我从字面上复制了链接中的代码。我检查了SQL Fiddle,代码工作正常。我正在使用 XAMPP 。这可能是原因吗?如果是,是否有任何解决方法可以获得上述工作?

我真的很感激一些帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

变量赋值必须在子查询中。

select
    id,
    first_column,
    second_column,
    row_num
from 
    (select 
        m.*,
        @num := if(@first_column = first_column, @num + 1, 1) as row_num,
        @first_column:=first_column as c
    from mytab m
    cross join (select @first_column:='',@num:=0) r --this was in the outer query previously
    order by first_column,id
    ) t