我在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
最佳答案
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。如果一则广告可以包含多个图片,用户或类别,则您将需要更复杂的查询。
关于php - 如何在mysql select语句上联接4个表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5227313/