在两个MySQL表中组合数据

时间:2015-08-03 01:47:43

标签: mysql join

我无法将数据合并到在线游戏社区的表格之间。在我的数据库中,我有两个表(及其中的值):

Statsme2 ----> bodyid head chest胃左臂右臂leftleft rightleg

玩家---> lastName,playerid,shots

来自" Statsme2"的玩家是"玩家" ...中的同一个玩家,并且对应于"玩家"中的lastName。这是用户姓名的打印输出。

我希望数据显示为:

姓名|头部投篮的百分比

user1 | %到这里

user2 | %到这里

我得到它打印统计数据,但每个用户不是一行,而是为每个用户吐出数百行。

如何将每个用户的所有实例合并为一行?请参阅附件中的图片(Statsme2表):

An image of the Statsme2 table

    <?php
    // Make a MySQL Connection
connection data in here
    // Get specific data from table
    $result = mysql_query("SELECT ((shots)/(BodyParts.head) * 100) as 'Head', Player.lastName as 'Name', shots
    FROM hlstats_Events_Statsme2 BodyParts
    JOIN hlstats_Players Player ON BodyParts.playerId=Player.playerId
    WHERE Player.lastName NOT LIKE '%BOT%' AND Player.lastName NOT LIKE '%infected%' AND Player.lastName NOT LIKE '%witch%' AND connection_time > '36000';")
    or die(mysql_error()); 
    echo "<table class=\"tablesorter-blackice\">";
    echo "<thead>";
    echo "<tr><th>Player</th><th>% Of Head Shots</th></tr>";
    echo "</thead>";
    echo "<tbody>";
    // keeps getting the next row until there are no more to get
    while($row = mysql_fetch_array( $result )) {
        // Print out the contents of each row into a table
        echo "<tr><td>"; 
        echo $row['Name'];
        echo "</td><td>";
        echo round($row['Head'],2)."%";
        echo "</td></tr>"; 
    } 
    echo "</tbody>";
    echo "</table>";
    mysql_close();
    ?>

这就是它的外观,而不是将每个行的所有行平均为一行:

Current output

2 个答案:

答案 0 :(得分:1)

您需要按“lastName”列对结果进行分组。然后查询就像这样,

SELECT players.lastName, Statsme2.head
FROM players
JOIN Statsme2
ON players.playerid = Statsme2.playerid
GROUP BY players.lastName

答案 1 :(得分:0)

JOIN运算符的使用方式与过去不同,我怀疑它是你遇到的问题。您可能想尝试以下任一语法:

SELECT [ stuff from both tables ]
FROM A
INNER JOIN B ON A.id = B.id
WHERE [ whatever, omitting equality of B.id and A.id ]

SELECT [ stuff from both tables ]
FROM A, B
WHERE [ whatever, including the equality of B.id and A.id ]