我使用PHP脚本从Android到达MySQL数据库,我正在使用JSON解析返回的值。它工作正常。我的问题是关于MySQL。
我有两个名为country
和geography
的表,其结构如下。
国家/地区表包含以下列:
country_id* | country_name and 20 more column...
地理位置表包含以下列:
geography_id* | location and 15-20 more column...
(*)表示主键
<?php
//some connection properties here....
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$sql = "SELECT * FROM countries, geography WHERE country_id = '". $_POST["COUNTRY_ID"]."'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
运行此脚本后返回不需要的值。假设,当我请求country_id = 1
时,JSON返回geography
表的所有行。我只想检索geography_id=1
的行。我必须使用外键来解决我的问题。或者另一种方式?
答案 0 :(得分:1)
最好的办法是通过添加geography
列(或类似内容)来为(可能)country_id
表添加外键:
该列将包含它在countries
表中引用的国家/地区的ID。然后你的查询看起来像这样:
"SELECT *
FROM `geography`
INNER JOIN `countries` on geography.country_id = countries.country_id
WHERE geography.country_id = {$_POST["COUNTRY_ID"]}";
有关联接的更多信息,请查看此处 - 这是我读过的最好的文章之一:http://www.sitepoint.com/understanding-sql-joins-mysql-database/