简体   繁体   English

如何从PHP中的SQL表获取行位置

[英]How to get row position from sql table in Php

I need the 'position (row)' from an SQL table using my PHP script. 我需要使用PHP脚本从SQL表中获取“位置(行)”。 I tested my SQL statement and it worked fine. 我测试了我的SQL语句,它运行良好。 The output is correct. 输出正确。

My SQL statement: 我的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';

Output: 输出:

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

But if i put it in PHP: 但是,如果我把它放在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';";

it shows me a errant query . 它向我显示了一个errant query

I also tried something like this: 我也尝试过这样的事情:

$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';";

Output: 输出:

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

Thanks to VolkerK, i solved that Problem with: 感谢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);

I understand better now. 我现在更好了。

The trick is not to get the position, it's to get the number of people that have a better score than the user. 诀窍不是获得位置,而是获得比用户得分更高的人数。

SQL: 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

The contatenated query is more complicated, but didn't need to order the whole table, and looks like 受污染的查询更加复杂,但是不需要对整个表进行排序,看起来像

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

Or, to limit the join by filtering before joining, like : 或者,通过在加入之前进行过滤来限制加入,例如:

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
    )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM