簡體   English   中英

如何在一個語句中加入四個MySQL表

[英]How do I join four MySQL tables in one statement

這是我目前沒有加入的聲明

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM