开发者

How do I join four MySQL tables in one statement

开发者 https://www.devze.com 2023-03-14 05:50 出处:网络
This is my current statement without join $s1 = \"SELECT * FROM states WHERE statecode=\'\".intval($getStateCode).\"\'

This is my current statement without join

$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='".intva开发者_高级运维l($getTownCode)."'"; 

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

It's possible to join all of my tables in one statement? Let me know.


<?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)."'";


This should get you started:

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


You might try this:

$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)."'";
0

精彩评论

暂无评论...
验证码 换一张
取 消