如何从第一个选择查询结果集中多次运行选择查询?

时间:2015-10-22 06:15:31

标签: php mysql

我似乎无法弄清楚如何从查询中获取结果并在另一个查询中使用它们。为了保持简单,我只想说我有一个名为saved_players的表,并且设置如此......

Username     playername
user1         player1
user1         player2
user2         player1
user1         player3
user3         player1

以下是我用于仅为登录用户回显所有这些信息的查询。

$query = "SELECT * FROM saved_players WHERE username = '".$_SESSION['login']."'";

$result = $conn->query($query);

if (mysqli_num_rows($result) > 0) {
// output data of each row

while($row = mysqli_fetch_assoc($result)) {

    echo "
    <table class='tablebox' width='300' border='0' cellspacing='0'>
    <tr>


    <td width='200' style='color: #4f4e4e; font-size: 19px;'>". $row["[playername"]."</td>

    </tr>

    </table>";


    }
} 

?> 

如果用户“user1”已登录,则当然会显示

player1
player2
player3

如何使用这些名称运行新查询?所有这一切的最终目标是从结果中获取每个玩家的名字(在本例中为player1,玩家2和玩家3)并运行类似于此的查询

$query= "SELECT COUNT(playername) AS Totalnumber FROM saved_players WHERE playername = '' ";

我正在尝试计算所有用户将这些玩家添加到表saved_players的次数,并将该数量除以我拥有的成员数量。但是我只需要为登录用户添加到saved_players的玩家完成此操作。当然希望这对帮助有任何意义,我将不胜感激!

2 个答案:

答案 0 :(得分:0)

使用此查询: -

$query = "SELECT *,(SELECT COUNT(playername) FROM saved_players as tab1 
WHERE tab1.playername = tab1.playername) 
AS Totalnumber FROM saved_players as tab2 
WHERE username = '".$_SESSION['login']."'"
像这样的Mysql查询: -

SELECT *,(SELECT COUNT(playername) FROM saved_players as tab1 
    WHERE tab1.playername = tab1.playername) 
    AS Totalnumber FROM saved_players as tab2 
    WHERE username = 'user1'

答案 1 :(得分:0)

试试这段代码逻辑:

         <?php
            $query = "SELECT * FROM saved_players WHERE username = '".$_SESSION['login']."'";

            $result = $conn->query($query);

            if (mysqli_num_rows($result) > 0) {
            // output data of each row

            while($row = mysqli_fetch_assoc($result)) {

                echo "
                <table class='tablebox' width='300' border='0' cellspacing='0'>
                <tr>


                <td width='200' style='color: #4f4e4e; font-size: 19px;'>". $row["[playername"]."</td>";
            /*
            Your logic can be placed here...

 $query= "SELECT COUNT(playername) AS Totalnumber FROM saved_players WHERE playername = '' GROUP BY playername HAVING Totalnumber > 0";

    The above is only an example...
    but if you still wish to get 0 number of players then disregard the HAVING Part
    --------------------------------------------------------------------

       // In your inner SQL query you may use group by with HAVING
            get the value you expect in this query

            */



                echo"</tr>

                </table>";


                }
            } 

            ?>

希望这会有所帮助