gpt4 book ai didi

php - SQL - 加入 2 个表,但如果 1 个表为空则返回所有

转载 作者:太空宇宙 更新时间:2023-11-03 12:12:26 25 4
gpt4 key购买 nike

使用 CodeIgniter 事件记录:

    $country = $_SESSION['search'];
$min_price = $_SESSION['min_price'];
$max_price = $_SESSION['max_price'];
$condition = "";
$this->db->select('*,attachments.title as image');
$this->db->from('details');
$this->db->join('attachments', 'attachments.parent = details.id');
$this->db->where('attachments.type', 'quotes');
if ($country != '')
{
$condition .= "(details.service_location IN ('" . $country . "') OR details.country in ('" . $country . "'))";

$this->db->where($condition);
}

$this->db->where('details.price_range_from >=', $min_price);
$this->db->where('details.price_range_to <=', $max_price);


$this->db->group_by("attachments.parent");
$this->db->order_by("details.created_on", "asc");
$query = $this->db->get();
$result = $query->result();
return $result;
}

我有 2 个表,其中包含详细信息和附件,我想对它们进行联接。

表格详情中总会有记录。

当表附件中有行时,我希望查询将表详细信息和表附件匹配的所有行都翻过来。 (即表现得像内连接)

但是,如果表附件为空,我想返回表详细信息中的所有内容。

并在 where 条件下检查表附件。

这可以在 1 个查询中完成吗?

谢谢。

最佳答案

使用 LEFT OUTER JOIN 而不是 JOIN

FROM (details) 
LEFT OUTER JOIN attachments ON attachments.parent = details.restaurant_id

更新

当然

GROUP BY details.restaurant_id

而不是 attachments.parent

关于php - SQL - 加入 2 个表,但如果 1 个表为空则返回所有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23670278/

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