问题
I have TABLE 1 that contains zip codes and their location information (i.e longitude, latitude, etc), TABLE 2 contains the properties with their addresses... I need to connect the longitude and latitude of the zipcodes in the TABLE 1 to the addresses in TABLE 2 >>
to be able to create a search that gives the nearest properties in a (x)mile radius of a specific zip code...
I'm not sure how to do this. Do I need to combine the two tables? Or can I do a search that pulls info from both simultaneously?
Thanks!
回答1:
First of all, you need to build relatinship between these two tables, you can use Zipcode, or you can use surrogate key. Then you can join the two table to do search.
回答2:
you should do a select on the zip codes table for what zip codes match your coordinates, then join the addresses table where the address has that zip code.
http://dev.mysql.com/doc/refman/5.0/en/join.html
回答3:
If I understand your problem correctly, the issue is that the server won't be able to tell how close or far each address are from each other while two of them have the same zipcode.
Let me rephrase. If you have addresses A, B and C and they all have the same zipcode, there is no way (unless you have coordinates in the address table too) to tell how close is A from B or C.
A possible work around, as you've been told is to use only the zipcode to relate the tables. Then you just need a simple join query like this:
SELECT <fields>
FROM TABLE1 a
join TABLE2 b
on
( a.zipcode=b.zipcode )
WHERE a.zipcode=<Your_search_here>
In that example, your zipcode doesn't even have to be in your selected fields.
I hope this helps =)
回答4:
This is taken from a site I made, that a client skipped town on and never paid me for - enjoy:
<?php
$res = mysqli_query($dh,
"SELECT `items`.`id`, `items`.`title`, `items`.`postcode`, `geodata`.`lat`,
`geodata`.`long`, (6371.009*acos(cos(radians(" . $_SESSION['lat'] . "))*
cos(radians(`geodata`.`lat`))*cos(radians(`geodata`.`long`)-radians(" .
$_SESSION['long'] . "))+sin(radians(" . $_SESSION['lat'] . "))*
sin(radians(`geodata`.`lat`)))) AS `distance`
FROM `items`, `geodata`
WHERE `geodata`.`postcode` = `items`.`postcode`
ORDER BY `distance` ASC"
);
echo '<table>';
while($item = mysqli_fetch_assoc($res))
{
echo '<tr>' .
'<td><a href="/' . $item['id'] . '">' . $item['title'] . '</a></td>' .
'<td>' . $item['postcode'] . ' (' . number_format($item['distance']) . 'km away)</td>' .
'</tr>';
}
echo '</table>';
?>
In this example, $_SESSION['lat']
and $_SESSION['long']
contain the user's location.
A MySQL table like this called geocode
is also needed:
postcode | lat | long
200 | -35.2765521 | 149.1220236
810 | -12.3808934 | 130.8773842
(these were taken from Australia).
This returns a list of items
, nearest first, with the distance shown in km.
来源:https://stackoverflow.com/questions/15512372/applying-information-from-one-table-to-a-separate-table-in-same-database