如何在一个语句中加入四个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).\"\'\"; 
是否可以在一条语句中连接我的所有表?让我知道。     

解决方法

        
<?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).\"\'\";
    ,        这应该使您开始:
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
    ,        您可以尝试以下方法:
$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).\"\'\";