2011-06-18 76 views
1

這是我沒有當前語句加入如何加入4代MySQL表在一個聲明中

$s1 = "SELECT * 
     FROM states 
     WHERE 
     statecode='".intval($getStateCode)."' 
     "; 

$s2 = "SELECT * 
     FROM county 
     WHERE 
     statecode='".intval($getStateCode)."' 
     AND 
     countycode='".intval($getCountyCode)."' 
     "; 

$s3 = "SELECT * 
     FROM town 
     WHERE 
     statecode='".intval($getStateCode)."' 
     AND 
     countycode='".intval($getCountyCode)."' 
     AND 
     towncode='".intval($getTownCode)."'"; 

$s4 = "SELECT * 
     FROM villages 
     WHERE 
     statecode='".intval($getStateCode)."' 
     AND 
     countycode='".intval($getCountyCode)."' 
     AND 
     towncode='".intval($getTownCode)."' 
     AND 
     villagecode='".intval($getVillageCode)."'"; 

有可能參加所有我的表在一個聲明?讓我知道。

+0

你擔心失去信息?你想要那些沒有村莊的州嗎? 你在找什麼?所有的村莊和他們的城鎮,縣和州的信息? 這可以完成,但你會有很多重複的數據。 – Virmundi

回答

3
<?php 
$query = "SELECT * 
FROM state s 
JOIN county c ON s.statecode = c.statecode 
JOIN town t ON s.statecode = t.statecode AND c.countycode = t.countycode 
JOIN villages v ON s.statecode = v.statecode AND c.countycode = v.countycode AND t.towncode = v.towncode 
WHERE 
     s.statecode='".intval($getStateCode)."' 
     AND 
     c.countycode='".intval($getCountyCode)."' 
     AND 
     t.towncode='".intval($getTownCode)."' 
     AND 
     v.villagecode='".intval($getVillageCode)."'"; 
+0

非常感謝!它的工作很棒;) – nirmala

1

這應該讓你開始:

SELECT * FROM state s 
INNER JOIN county c ON c.statecode = s.statecode 
INNER JOIN town t ON t.statecode = s.statecode AND t.countycode = c.countycode 
INNER JOIN villages v ON v.statecode = s.statecode AND v.countycode = c.countycode AND v.towncode = t.towncode 
0

你可以試試這個:

$sql = "select * from villages V 
    join town T on T.towncode=V.towncode 
    join county C on C.countycode=V.countycode 
    join state S on S.statecode=V.statecode 
    where V.statecode='".intval($getStateCode)."' 
    and V.countycode='".intval($getCountyCode)."' 
    and V.towncode='".intval($getTownCode)."' 
    and V.villagecode='".intval($getVillageCode)."'";