MySQL $i++ equivalent

2019-08-17 05:00发布

Query I'm using:

SELECT COUNT(*),
    SUM(amount) AS amount,
    FROM_UNIXTIME(added, '%W (%e/%m)') AS daily
FROM affiliates_earnings
WHERE added >= '1319074836'
    AND added <= '1319679636'
GROUP BY daily

Output:

+----------+--------+-------------------+
| COUNT(*) | amount | daily             |
+----------+--------+-------------------+
|        1 |    195 | Tuesday (25/10)   |
|        4 |    470 | Wednesday (26/10) |
+----------+--------+-------------------+

What I would like to show up:

+-------+----------+--------+-------------------+
| i     |COUNT(*)  | amount | daily             |
+-------+----------+--------+-------------------+
| 1     |        1 |    195 | Tuesday (25/10)   |
| 2     |        4 |    470 | Wednesday (26/10) |
+-------+----------+--------+-------------------+

Essentially i would be the sequential number (i.e. 1,2,3,4,5,6...).

How would I accomplish this?

2条回答
闹够了就滚
2楼-- · 2019-08-17 05:27

Without ROW_NUMBER(), you can fake it per this answer or this one:

  SELECT @i := @i + 1 AS i, COUNT(*), ...
    FROM affiliates_earnings
    JOIN (SELECT @i := 0) dummy
   WHERE ...
GROUP BY ...;
查看更多
聊天终结者
3楼-- · 2019-08-17 05:33

Doing this is almost nonsense, but if your really want, try this way:

SELECT 
    @i:=@i+1 as i,
    COUNT(*),
    SUM(a.amount) AS amount,
    FROM_UNIXTIME(a.added, '%W (%e/%m)') AS daily
FROM affiliates_earnings a, (SELECT @i:=0) b
WHERE a.added >= '1319074836'
    AND a.added <= '1319679636'
GROUP BY a.daily
查看更多
登录 后发表回答