2011-06-18 10 views
1

これは参加どのように私は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)."'"; 

のない私の現在の文です。これは1つのステートメントで私のテーブルのすべてに参加することが可能ですか?お知らせ下さい。

+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)."'"; 
関連する問題