我有两个表,一个叫area,一个叫area covered。表区域包含邮政编码和地区字段。
例句:
区域表包含邮编 - AB10 地区 -香港仔
区域覆盖表包含id - 1 邮编 - AB10 日期 - 1364989057
现在我有一个搜索邮政编码或地区的表单。我使用JQuery的自动完成,可以获得邮政编码或地区,但不能两者兼得。
现在我有:
$result = $db->query("SELECT DISTINCT `postcode` FROM `areaCovered` WHERE `postcode` LIKE '%$search%' ORDER BY `postcode` ASC") or die('Something went wrong');
然后我使用从数据库结果中检索到的数据并放入JSON:
$json = '[';
$first = true;
while ($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['postcode'].'"}';
}
$json .= ']';
echo $json;
如何首先连接两个表来搜索仅存在于区域覆盖表中的邮政编码或地区,然后输出结果是地区还是邮政编码?
我希望这对你有意义,
谢谢
您应该使用group by
代替distinct
,并将它们连接起来。
select
a.`postcode` as postcode,
a.`region` as region,
from
`area` as a
inner join
`areaCovered` as ac
on
a.`postcode`=ac.`postcode`
where
a.`postcode` like '%$search%'
or
a.`region` like '%$search%'
group by
a.`postcode`
order by
a.`postcode` asc
最好我只是json_encode()
整个结果集和解析它的客户端,但它看起来像你可能需要有一个特殊的JSON结构的jQuery插件?
$list = array();
while ($row = $result->fetch_assoc()) {
array_push(
$list,
array('value' => $row['postcode'] . ', ' . $row['region'])
);
}
echo json_encode($list);
这将创建一个JSON结构,看起来像;
[
{
"value": "123 45, Region 1"
},
{
"value": "678 90, Region 2"
},
...
]