2011-03-08 55 views
0

我在MySQL中有4個表要加入。示例如何在mysql select語句上連接4個表?

$select = $db->query("SELECT * 
         FROM ads 
         WHERE ad_pic='1' 
         AND ad_status = '1' 
        ORDER BY ad_id DESC LIMIT 0,4"); 

while ($fetch = $db->fetch($select)) { 

    $iquery = $db->query("SELECT * 
          FROM images 
          WHERE img_ads_id = '" . intval($fetch['ad_id']) . "' 
          AND img_status = '1' 
          LIMIT 1"); 
    $thumb = $db->fetch($iquery); 

    $uselect = $db->query("SELECT * 
          FROM users 
          WHERE user_id = '".intval($fetch['ad_userid'])."' 
           AND user_status = '1' 
          LIMIT 1"); 
    $ufetch = $db->fetch($uselect); 

    $cselect = $db->query("SELECT * 
          FROM category 
          WHERE cat_slug = '".safe_func($fetch['ad_category'])."' 
          LIMIT 1"); 
    $cfetch = $db->fetch($cselect);   

} 

我想知道如何在一個select語句中加入這些語句。


ads table 

ad_id ad_userid ad_category 
------------------------------- 
1  2   5 

images table 

img_id img_ads_id 
------------------------------- 
1  1   

users table 

user_id  user_name 
------------------------------- 
2   John 

category table 

cat_id cat_name 
------------------------------- 
5  Vehicles  
+2

你可以給我們模式中與你想加入的四張表相關的部分嗎? – 2011-03-08 01:28:55

+0

廣告和圖片之間是否存在1對1的關係?廣告和用戶之間?廣告和類別之間? (我猜是的。) – 2011-03-08 01:34:44

+0

作爲布賴恩問,給我們完整的架構。需要知道每個表中的外鍵和私鑰,以瞭解它們是如何關聯的。 – coder 2011-03-08 01:36:33

回答

9
SELECT * 
FROM ads AS a 
LEFT JOIN images AS i ON i.img_ads_id = a.ad_id AND i.img_status = 1 
LEFT JOIN users AS u ON u.id = a.ad_userid AND u.user_status = 1 
LEFT JOIN category AS c ON c.cat_slug = a.ad_category 
WHERE a.ad_pic = 1 
AND a.ad_status = 1 
ORDER BY a.ad_id DESC 
LIMIT 0,4 

如果廣告必須有一個圖像,用戶或類別,你可以使用JOIN代替LEFT JOIN。如果廣告可以擁有多個圖片,用戶或類別,則需要更復雜的查詢。

+0

感謝Patrick Fisher :) – haha 2011-03-08 02:11:16