如何在一个语句中加入四个MySQL表

时间:2011-06-18 03:43:49

标签: mysql sql

这是我目前没有加入的声明

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

可以在一个声明中加入我的所有表吗?让我知道。

3 个答案:

答案 0 :(得分: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)."'";

答案 1 :(得分: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

答案 2 :(得分: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)."'";