我的数据库中有两个表 - " region"和"吸引力"。我做了一个JOIN查询,它将从这两个数据中获取数据,而我正在显示它。这是我的代码:
$regionsId = $_GET['region'];
//$sql = "SELECT `RegionID`, `RegionName` FROM `region` WHERE `RegionID`='$regionsId'";
//$sql = "SELECT `AttractionID`, `Name`, `imglink2` FROM `attractions` WHERE `RegionID`='$regionsId'";
$sql ="SELECT *
FROM region
INNER JOIN attractions WHERE region.RegionID = '$regionsId' AND attractions.RegionID = '$regionsId'";
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['RegionName'];
echo "<a href='attraction.php?village=" . $row['AttractionID'] . "'>" . "<br />" .
$row['Name'] .
"<br />" .
"<img src='" . $row['imglink2'] . "' height='130' width='150'>
</a>";
}
mysql_free_result($result);
?>
我的问题是当我显示echo $ row [&#39; RegionName&#39;];我显示的每个景点都会多次显示。我怎样才能使它只显示一次? 谢谢。
答案 0 :(得分:0)
尝试GROUP BY
$sql ="
SELECT *
FROM region
LEFT JOIN attractions ON region.RegionID = attractions.RegionID
WHERE region.RegionID = '$regionsId'
AND attractions.RegionID = '$regionsId'
GROUP BY region.RegionID" ;
答案 1 :(得分:0)
使用此:
$sql = "SELECT DISTINCT *
FROM region
LEFT JOIN attractions ON region.RegionID = attractions.RegionID
WHERE region.RegionID = '$regionsId'
AND attractions.RegionID = '$regionsId'
GROUP BY region.RegionID";
答案 2 :(得分:0)
评论有点长。 SQL将以表格格式返回值,所有“单元格”完全填入:
region attraction
A 1
A 2
A 3
B 1
B 5
如果你想要这种形式:
A 1,2,3
B 1,5
然后数据库是合适的:
SELECT r.*, group_concat(a.AttractionId)
FROM region r LEFT JOIN
attractions a
ON r.RegionID = a.RegionID
WHERE r.RegionID = '$regionsId'
GROUP BY r.RegionID;
如果你想要这种形式:
region attraction
A 1
2
3
B 1
5
然后你应该在应用层进行工作。可以在数据库中进行设置,但它在处理表时“违反”SQL的性质。并且,在显示结果时循环显示结果非常容易。
答案 3 :(得分:0)
最简单的方法是将order by RegionName
添加到您的查询中,然后更改代码以监视区域更改并仅在发生更改时显示,如下所示:
$prevRegionName = ''; // fill variable with something that won't be matched in first comparison
while ($row = mysql_fetch_assoc($result)) {
$currentRegionName = $row['RegionName']; // push current region to variable
if ($currentRegionName != $prevRegionName) echo $row['RegionName']; // print region only if it changed
echo "<a href='attraction.php?village=" . $row['AttractionID'] . "'>" . "<br />" .
$row['Name'] .
"<br />" .
"<img src='" . $row['imglink2'] . "' height='130' width='150'>
</a>";
$prevRegionName = $currentRegionName; // save current region to compare it in next interaction
}