2013-04-07 13 views
0

我正在通過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

回答

1

最好的辦法是要通過增加柱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/