据说我在PHP中有这个sql结果($ myresults = mysql_fetch_ ... assoc / row / array):
SELECT table1.name as name, sum(table2.numbers) as numbers FROM table2 INNER JOIN
table1 ON table2.fk_id = table1.id GROUP BY name ORDER BY numbers DESC
---------------
| John | 800 |
---------------
| Mark | 500 |
---------------
| Bill | 300 |
---------------
所以我被记录为Mark($ _SESSION ['name'] ==“Mark”)并且我想知道'Mark'所在的行#(在这种情况下,行号1,考虑到第一行是0)。
如何通过PHP获取?
...谢谢
编辑:将其视为高分或排行榜表,我不需要用户ID,而是用户所在的行...
答案 0 :(得分:1)
您应该以这种方式使用用户定义的变量:
SELECT table1.name as name, sum(table2.numbers) as numbers,
@rank := @rank + 1 rank
FROM table2
CROSS JOIN (SELECT @rank := 0) init
JOIN table1 ON table2.fk_id = table1.id
GROUP BY name
ORDER BY numbers DESC
经过一番思考后,小组可能会给你带来一些UDV计数的麻烦。这是另一种选择,但效果不如前一种方法。
SELECT *, @rank := @rank + 1 rank FROM (
SELECT table1.name as name, sum(table2.numbers) as numbers
FROM table2
JOIN table1 ON table2.fk_id = table1.id
GROUP BY name
) s
CROSS JOIN (SELECT @rank := 0) init
ORDER BY numbers DESC
无论如何,我建议直接用PHP计算。这将更加灵活和高效。
答案 1 :(得分:0)
修改SQL以选择主ID以及其他数据:
SELECT
table1.id as id,
table1.name as name,
sum(table2.numbers) as numbers
FROM
table2
INNER JOIN
table1 ON table2.fk_id = table1.id
GROUP BY
name
ORDER BY
numbers DESC