如何在mysql select语句中加入4个表?

时间:2011-03-08 01:26:41

标签: php mysql sql greatest-n-per-group

我在MySQL中有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       

1 个答案:

答案 0 :(得分: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。如果广告可以包含多个图片,用户或类别,则需要更复杂的查询。