Php 查询多个表-返回1个匹配项
我有两张桌子:一张餐馆的桌子和一张区域的桌子。Addresses表中的“EntryID”键是一个与restaurant表中每个记录的主键相同的数字。所以EntryID是一个外键。我希望能够修改我的PHP选择脚本,以便在这两个表之间搜索数据库。以下是我现在拥有的:Php 查询多个表-返回1个匹配项,php,mysql,sql,Php,Mysql,Sql,我有两张桌子:一张餐馆的桌子和一张区域的桌子。Addresses表中的“EntryID”键是一个与restaurant表中每个记录的主键相同的数字。所以EntryID是一个外键。我希望能够修改我的PHP选择脚本,以便在这两个表之间搜索数据库。以下是我现在拥有的: $RPrice = $_GET["price"]; $RType = $_GET["type"]; $RAtmosphere = $_GET["RAtmosphere"]; $RArea = $_GET["RArea"
$RPrice = $_GET["price"];
$RType = $_GET["type"];
$RAtmosphere = $_GET["RAtmosphere"];
$RArea = $_GET["RArea"];
if (!empty($RPrice)) $w[]="Foodlist.price='".mysql_real_escape_string($RPrice)."'";
if (!empty($RType)) $w[]="Foodlist.ftype='".mysql_real_escape_string($RType)."'";
if (!empty($RAtmosphere)) $w[]="Foodlist.atmosphere='".mysql_real_escape_string($RAtmosphere)."'";
if (!empty($RArea)) $w[]="Addresses.area='".mysql_real_escape_string($RArea)."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$sql="SELECT Foodlist.ID, Foodlist.name from Foodlist JOIN Addresses ON (Foodlist.ID = Addresses.EntryID) $where";
$result= mysql_query($sql);
while($row=mysql_fetch_array($result)){
$ID=$row['ID'];
echo "<a class=\"cross-link\" href=\"javascript:ajaxpage('result.php?id=$ID', 'results2'); ajaxpage('videoloader.php?id=$ID', 'results1');\">".$row['name']."</a><div id=\"contentarea\"></div>";
}
$RPrice=$\u GET[“price”];
$RType=$\u GET[“type”];
$RAtmosphere=$\u获取[“RAtmosphere”];
$RArea=$_GET[“RArea”];
如果(!empty($RPrice))$w[]=“Foodlist.price=”.mysql\u real\u escape\u string($RPrice)。“”;
如果(!empty($RType))$w[]=“Foodlist.ftype=”。mysql\u real\u escape\u string($RType)。“”;
如果(!empty($RAtmosphere))$w[]=“Foodlist.atmosphere=”.mysql\u real\u escape\u string($RAtmosphere)。“”;
如果(!empty($RArea))$w[]=“Addresses.area=”.mysql\u real\u escape\u string($RArea)。”;
if(count($w))$where=“where.”内爆('AND',$w);else$where='';
$sql=“从(Foodlist.ID=Addresses.EntryID)$where上的Foodlist连接地址中选择Foodlist.ID,Foodlist.name”;
$result=mysql\u查询($sql);
while($row=mysql\u fetch\u数组($result)){
$ID=$row['ID'];
回声“;
}
我已经注释掉了“区域”部分,因为这是需要更改的内容
我希望能够保持与以前相同的功能,但我希望能够跨多个区域记录进行搜索。我希望这是有道理的。如果你需要更多的澄清,请让我知道
Foodlist(表)包含以下列:ID、价格、类型和氛围
地址(表)包含以下列:EntryID、area
现在,查询假设所有这些列(entryID除外)都在foodList中。我需要查询从Addresses表中搜索区域。另外,我希望从每个ID的查询中返回1个结果。FoodList表中的一条记录可能在Addresses表中有多条对应的记录。在本例中,我只希望它返回与给定区域匹配的值
SELECT f.ID, name FROM Foodlist f JOIN Addresses a ON (f.ID = a.EntryID) $where
我相信这足以满足您的需要。这行不通。例如,假设Foodlist“12”中有一个ID。在地址表中,可能有两条与“12”关联的记录,一条为area=north,另一条为area=south。我应该只退一个。此查询还仅返回在addresses表中有记录的值。在这种情况下,加上限制1,把连接变成左连接,问题就解决了。