簡體   English   中英

SQL-連接2個表,但如果1個表為空則返回所有表

[英]SQL - join 2 tables but return all if 1 table empty

使用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個表格,分別說明詳細信息和附件,我想對它們進行聯接。

表詳細信息將始終包含記錄。

當表附件中包含行時,我希望查詢將表詳細信息和表附件匹配的所有行都變為。 (即表現得像內部聯接)

但是,如果表附件為空,我想返回表詳細信息中的所有內容。

並在何處檢查表附件。

這可以在1個查詢中完成嗎?

謝謝。

使用LEFT OUTER JOIN而不是JOIN

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

更新

而且當然

GROUP BY details.restaurant_id

而不是attachments.parent

盡管我認為這有點奇怪,但您可以使用的主要結構是:

inner join union select *, ... from details where 0 = (select count(*) from attachments where ...)

如果內部聯接不返回行,則第二個查詢將返回所有詳細信息。 如果內部聯接返回行,則第二個查詢將不返回任何內容,因為找到了附件(count(*)返回一些正值)。

我認為您可以自己填寫詳細信息。 我不保證表現出色。

使用兩個不同的查詢,檢查附件是否包含行,並使用內部聯接詳細信息運行查詢,否則從詳細信息表返回行

 IF EXISTS (SELECT * FROM @attachments where column1='')
   BEGIN
  SELECT * FROM attachments as atc 
  INNER JOIN details AS det ON   atc.parent = det.restaurant_id where column2=''
END
ELSE
  SELECT * FROM details  where column2=''

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM