如何从Php中的sql表中获取行位置

时间:2014-12-02 08:33:07

标签: php mysql sql

我需要'位置(行)'从使用我的PHP脚本的SQL表。我测试了我的SQL语句,它工作正常。输出正确。

我的SQL声明:

SET @rownum = 0; 
SELECT position, name,cash FROM (SELECT name, cash, @rownum := @rownum + 1 AS position FROM 'my_DB'.'Cash' ORDER BY cash DESC ) AS t WHERE name = 'user44';

输出:

"position":44,"name":"user44","cash":"5600"

但如果我把它放在PHP中:

$query="SET @rownum = 0; SELECT position, name,cash FROM (SELECT name, cash, @rownum := @rownum + 1 AS position FROM 'my_DB'.'Cash' ORDER BY cash DESC ) AS t WHERE name = 'user44';";

它显示了errant query

我也试过这样的事情:

$query="SELECT position, name,cash FROM (SELECT name, cash, @rownum := @rownum + 1 AS position FROM 'my_DB'.'Cash' ORDER BY cash DESC ) AS t WHERE name = 'user44';";

输出:

"position":null,"name":"user44","cash":"5600"

感谢VolkerK, 我解决了这个问题:

$query = "SET @rownum =0;"; $result = mysql_query($query,$link) or die('Errant query: '.$query); $query="SELECT position, name,cash FROM (SELECT name, cash, @rownum := @rownum + 1 AS position FROM 'my_DB'.'HSCash' ORDER BY cash DESC ) AS t WHERE name = 'user44'"; $result = mysql_query($query,$link) or die('Errant query: '.$query);

1 个答案:

答案 0 :(得分:0)

我现在明白了。

诀窍不是要获得这个位置,而是要获得比用户更好的分数。

SQL:

// Get how much cash the user make
SELECT cash
FROM mydb.cash
WHERE name = :name;

// Get how many people did better + 1
SELECT COUNT(*)+1
FROM mydb.cash
WHERE cash > :cash

连续查询更复杂,但不需要对整个表进行排序,看起来像

SELECT position, name, cash
FROM mydb.cash
JOIN (
    SELECT COUNT(*)+1 AS position
    FROM mydb.cash
    WHERE cash > (
        SELECT cash
        FROM mydb.cash
        WHERE name = :name
    )
)
WHERE name = :name

或者,在加入前通过过滤来限制联接,例如:

SELECT position, name, cash
FROM (
    SELECT name, cash
    FROM mydb.cash
    WHERE name = :name
)
JOIN (
    SELECT COUNT(*)+1 AS position
    FROM mydb.cash
    WHERE cash > (
        SELECT cash
        FROM mydb.cash
        WHERE name = :name
    )
)