dongwei2030 2014-12-02 08:33
浏览 37

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

I need the 'position (row)' from an SQL table using my PHP script. I tested my SQL statement and it worked fine. The output is correct.

My SQL statement:

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:

$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.

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:

$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条回答 默认 最新

  • doulu3865 2014-12-02 09:29
    关注

    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:

    // 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
        )
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?