嗨大家好我正在学习如何通过以下在线教程编写代码(php和mysql),并从头开始构建我的第一个网站。
我很难解决问题而且我不知道在Google中获得结果的最佳搜索关键字。我希望有人可以提供帮助。
我熟悉
SELECT ... FROM ... JOIN ... ON ...
并且在使用直接相关的表时它非常好用但是当一个表是“远程相关”时(我不知道如何用这句话)然后我在mysql中出错了。
请参阅下图。 http://i.stack.imgur.com/mfNXT.png 我有5张桌子。
我想使用类似于
的代码输出html表"SELECT horseRaces.ID, horseRaces.stall, horseRaces.draw, horses.name, horses.birth, horseRaces.win, horseRaces.place, horseStatus.name
FROM horseRaces
JOIN horses ON horseRaces.horseID = horses.ID
JOIN horseStatus ON horseRaces.horseStatusID = horseStatus.ID
ORDER BY stall"
希望有人可以帮助我,因为我很难过。我的所有谷歌搜索都会带来内部联接和外部联接结果。
答案 0 :(得分:0)
坚持你的写作风格:
SELECT
horseRaces.ID
,horse.Name
,country.Name
,horseGender.Name
,jockey.Name
FROM horseRaces
JOIN horses ON horseRaces.HorseID = horses.ID
JOIN jockey ON horseRaces.JockeyID = jockey.ID
JOIN country ON horses.CountryID = country.ID
JOIN horseGender ON horses.GenderID = horseGender.ID
ORDER BY horseRace.ID, horse.ID
应该生成您正在寻找的表格。
我建议为每个表提供别名,这样你就不必每次都写出表名,在这种情况下,如果horseID,jockeyId,countryID和genderID不能为null,那么相应的连接应该是INNER(不要太担心,但是)
SELECT
hr.ID
,h.Name AS HorseName
,c.Name AS Country
,hg.Name AS HorseGender
,j.Name AS JockeyName
FROM horseRaces hr
INNER JOIN horses h ON hr.HorseID = h.ID
INNER JOIN jockey j ON hr.JockeyID = j.ID
INNER JOIN country c ON h.CountryID = c.ID
INNER JOIN horseGender hg ON h.GenderID = hg.ID
ORDER BY hr.ID, h.ID
答案 1 :(得分:0)
试试这个:
SELECT hr.ID, h.name, c.name, cg.name, j.name FROM horseRace hr
LEFT JOIN horses h ON h.ID = hr.horseID
LEFT JOIN country c ON h.countryID = c.ID
LEFT JOIN horseGender hg ON hg.ID = h.genderID
LEFT JOIN jockey j ON hr.jockeyID = j.ID
order by h.ID
答案 2 :(得分:0)
试试这个:
$sql="Select
hr.ID as ID,
h.name as HNAME,
c.name as COUNTRY,
hg.name as HGENDER,
j.name as JOKEY
from horseRase hr
left join hourses h
on hr.horseID = h.ID
left join country c
on h.countryID = c.ID
left join hourseGender hg
on h.genderID = hg.ID
left join jokey j
on hr.JokeyID=j.ID
ORDER BY hr.ID
";
$result = mysql_query($sql) or die();
echo "<table>
<tr>
<td>ID</td>
<td>HORSE NAME</td>
<td>COUNTRY</td>
<td>GENDER</td>
<td>JOKEY</td>
</tr>
";
while($row = mysql_fetch_array($result)){
$ID=$row['ID'];
$HORSE=$row['HNAME'];
$COUNTRY=$row['COUNTRY'];
$HGENDER=$row['HGENDER'];
$JOKEY=$row['JOKEY'];
echo "
<tr>
<td>$ID</td>
<td>$HORSE</td>
<td>$COUNTRY</td>
<td>$HGENDER</td>
<td>$JOKEY</td>
</tr>
";
}
echo "</table>"