gpt4 book ai didi

php - 如何在 mysql select 语句上连接 4 个表?

转载 作者:行者123 更新时间:2023-12-01 00:02:33 24 4
gpt4 key购买 nike

我在 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);

}

我想知道在一个选择语句中加入这些的方法。


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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com