MySQL表和JSON解析。外键还是不?

问题描述:

我正在通过PHP脚本从Android到达MySQL数据库,我正在使用JSON解析返回的值。它工作正常。我的问题是关于MySQL。MySQL表和JSON解析。外键还是不?

我有两个表名为countrygeography,它们的结构如下。

国家表中有这些列:

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

WHERE COUNTRY_ID =“...” AND geography_id = 1 – ChristopheCVB 2013-04-07 22:40:56

+0

我试过你的解决方案。但JSON只返回第一行。 – hakiko 2013-04-07 22:44:44

+0

2个表格之间的联系是什么? – ChristopheCVB 2013-04-07 22:45:54

最好的办法是要通过增加柱country_id(类似或东西)增加一个外键(可能)您geography表:

该列将包含它在引用该国的id countries表。然后,你的查询将是这个样子:

"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/