繁体   English   中英

尝试在简单的php系统中显示具有一对多关系的mysql数据?

[英]Trying to display in a simple php system mysql data with One to many relationship?

我已经从位置将FirstPositionID / SecondPositionID与PositionID(PRIMARY KEY)连接起来。 每个positionID都有一个职位名称。 由于我有2个由位置ID设置的玩家位置,所以php不应该打印我设置的每个ID的位置名称吗? 当我打印PositionName时,它会打印我已插入到我的位置表中的所有位置。 这是我的桌子

CREATE TABLE `players` (
`PlayerID` int(10) UNSIGNED NOT NULL,
`PlayerName` varchar(255) NOT NULL,
`CountryID` varchar(255) NOT NULL,
`FirstPositionID` int(11) UNSIGNED NOT NULL,
`SecondPositionID` int(10) UNSIGNED NOT NULL,
`Overall` int(11) UNSIGNED NOT NULL,
`Defence` int(11) NOT NULL,
`Speed` int(11) NOT NULL,
`Rebound` int(11) NOT NULL,
`Stamina` int(11) NOT NULL,
`TeamID` int(11) NOT NULL,
`Shooting` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16;

CREATE TABLE `positions` (
`PositionID` int(10) UNSIGNED NOT NULL,
`PositionName` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16;





//-----------php-----------------------

    $sql= "SELECT * from players,positions";
    $reg = mysqli_query($con,$sql);
    if(mysqli_num_rows($reg) > 0)
    {
        while($row = mysqli_fetch_assoc($reg))
        {
            echo "</br>Player:".$row['PlayerName']." Overall:".$row['Overall']." Position: ".$row['PositionName'];
        }

    }
    else 
    {
        echo "SQL error at: </br> ".$register."SYNTAX:</br>".mysqli_error($con)."</br>";
    }

结果:

Player:Agrabanis Overall:64 Position: Point Guard

Player:Athineou Overall:64 Position: Point Guard

Player:Agrabanis Overall:64 Position: Shooting Guard

Player:Athineou Overall:64 Position: Shooting Guard

Player:Agrabanis Overall:64 Position: Small Forward

Player:Athineou Overall:64 Position: Small Forward

Player:Agrabanis Overall:64 Position: Power Forward

Player:Athineou Overall:64 Position: Power Forward

Player:Agrabanis Overall:64 Position: Center

Player:Athineou Overall:64 Position: Center

由于我已经将第一玩家位置ID 5,4和第二玩家位置ID 2,1设置为第一玩家和第二玩家得分后卫,控球后卫(2,1位置),请仅打印Center,Power Forward(4,5位置ID) ids)

请使用left joininner join而不是交叉连接,并将您的SQL字符串更改为类似

SELECT pl.PlayerName, pl.FirstPositionID, pl.Overall,
pl.SecondPositionID, po1.PositionName AS FirstPositionName,
po2.PositionName AS SecondPositionName FROM players pl
LEFT JOIN positions po1 ON(pl.FirstPositionID = po1.PositionID )
LEFT JOIN positions po2 ON (pl.SecondPositionID = po2.PositionID )
LIMIT 0,100

另外,将您的while循环更改为

while($row = mysqli_fetch_assoc($reg)){
  echo "</br>Player:".$row['PlayerName']." Overall:".$row['Overall']." Position1: ".$row['FirstPositionName']." Position2:".$row['SecondPositionName '];
}

我认为这将帮助您...

暂无
暂无

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

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